Skip to content

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.

Windows 托盘与桌面图标、图片预览、修复配对后多一个确认框;修复位图读取错位

baiyuzea78913e36b36
diff --git a/client-core/cmd/copysyncd/main.go b/client-core/cmd/copysyncd/main.go
index 6f01aa8..18e1e38 100644
--- a/client-core/cmd/copysyncd/main.go
+++ b/client-core/cmd/copysyncd/main.go
@@ -322,7 +322,9 @@ func run(dataDir string) error {
Unpair: peerMgr.Unpair,
SignalingConnected: peerMgr.Connected,
Fetch: engine.Fetch,
+ FetchForPreview: engine.FetchForPreview,
ApplyToClipboard: engine.ApplyToClipboard,
+ ImagePreviewPath: engine.ImagePreviewPath,
CacheBytesUsed: blobs.Size,
Permission: func() clipboard.Permission {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
@@ -382,6 +384,11 @@ func run(dataDir string) error {
slog.Info("daemon 已就绪",
"port", port, "endpoint", paths.Endpoint, "cache", paths.Cache)
+ // 托盘属于后台服务:关掉界面后仍能打开它。独立数据目录用于测试,
+ // 不创建托盘,避免与用户正在运行的实例混在一起。
+ stopTray := startTray(ctx, cancel, dataDir == "")
+ defer stopTray()
+
// 系统事件(目前只有 Windows 上报):注销关机时正常退出,唤醒后立即重新探测网络
clipboard.SetSystemHooks(
func() {
diff --git a/client-core/cmd/copysyncd/platform_other.go b/client-core/cmd/copysyncd/platform_other.go
index 7c86c78..54c89f0 100644
--- a/client-core/cmd/copysyncd/platform_other.go
+++ b/client-core/cmd/copysyncd/platform_other.go
@@ -3,10 +3,13 @@
package main
import (
+ "context"
"io"
"os"
)
+func startTray(context.Context, context.CancelFunc, bool) func() { return func() {} }
+
// Mac 上这些都由 launchd 负责:日志重定向到文件、只运行一个实例、崩溃自动拉起。
func logOutput(string) io.Writer { return os.Stderr }
diff --git a/client-core/cmd/copysyncd/tray_windows.go b/client-core/cmd/copysyncd/tray_windows.go
new file mode 100644
index 0000000..a8c8047
--- /dev/null
+++ b/client-core/cmd/copysyncd/tray_windows.go
@@ -0,0 +1,278 @@
+//go:build windows
+
+package main
+
+// 托盘由 daemon 持有,界面关闭或尚未打开时仍可访问。
+// 独立线程泵消息:用户打开右键菜单时不能阻塞剪贴板线程。
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+var (
+ trayUser32 = windows.NewLazySystemDLL("user32.dll")
+ trayShell32 = windows.NewLazySystemDLL("shell32.dll")
+ trayKernel32 = windows.NewLazySystemDLL("kernel32.dll")
+ trayNotify = trayShell32.NewProc("Shell_NotifyIconW")
+ trayExtractIcon = trayShell32.NewProc("ExtractIconExW")
+ trayRegisterClass = trayUser32.NewProc("RegisterClassExW")
+ trayUnregisterClass = trayUser32.NewProc("UnregisterClassW")
+ trayCreateWindow = trayUser32.NewProc("CreateWindowExW")
+ trayDestroyWindow = trayUser32.NewProc("DestroyWindow")
+ trayDefWindowProc = trayUser32.NewProc("DefWindowProcW")
+ trayRegisterMessage = trayUser32.NewProc("RegisterWindowMessageW")
+ trayGetMessage = trayUser32.NewProc("GetMessageW")
+ trayTranslateMessage = trayUser32.NewProc("TranslateMessage")
+ trayDispatchMessage = trayUser32.NewProc("DispatchMessageW")
+ trayPostMessage = trayUser32.NewProc("PostMessageW")
+ trayPostQuitMessage = trayUser32.NewProc("PostQuitMessage")
+ traySetTimer = trayUser32.NewProc("SetTimer")
+ trayKillTimer = trayUser32.NewProc("KillTimer")
+ trayCreateMenu = trayUser32.NewProc("CreatePopupMenu")
+ trayAppendMenu = trayUser32.NewProc("AppendMenuW")
+ trayDestroyMenu = trayUser32.NewProc("DestroyMenu")
+ trayTrackMenu = trayUser32.NewProc("TrackPopupMenu")
+ trayGetCursorPos = trayUser32.NewProc("GetCursorPos")
+ traySetForeground = trayUser32.NewProc("SetForegroundWindow")
+ trayFindWindow = trayUser32.NewProc("FindWindowW")
+ trayLoadIcon = trayUser32.NewProc("LoadIconW")
+ trayDestroyIcon = trayUser32.NewProc("DestroyIcon")
+ trayGetModule = trayKernel32.NewProc("GetModuleHandleW")
+)
+
+const (
+ trayCallbackMessage = 0x8001 // WM_APP + 1
+ trayWMClose = 0x0010
+ trayWMDestroy = 0x0002
+ trayWMTimer = 0x0113
+ trayOpenCommand = 1
+ trayQuitCommand = 2
+)
+
+type trayNotifyData struct {
+ Size uint32
+ Window uintptr
+ ID, Flags, Callback uint32
+ Icon uintptr
+ Tip [128]uint16
+ State, StateMask uint32
+ Info [256]uint16
+ Version uint32
+ InfoTitle [64]uint16
+ InfoFlags uint32
+ GUID windows.GUID
+ BalloonIcon uintptr
+}
+
+type trayWindowClass struct {
+ Size, Style uint32
+ WndProc uintptr
+ ClsExtra, WndExtra int32
+ Instance, Icon, Cursor, Background uintptr
+ MenuName, ClassName *uint16
+ IconSmall uintptr
+}
+
+type trayMessage struct {
+ Window uintptr
+ Message uint32
+ WParam, LParam uintptr
+ Time uint32
+ X, Y int32
+ Private uint32
+}
+
+type windowsTray struct {
+ data trayNotifyData
+ taskbarCreated uintptr
+ uiPath string
+ quit context.CancelFunc
+}
+
+// 回调和状态只在托盘线程使用。回调 thunk 不能反复创建(Windows 数量有限)。
+var trayCallback = windows.NewCallback(trayWindowProc)
+var activeTray *windowsTray
+
+func startTray(ctx context.Context, quit context.CancelFunc, enabled bool) func() {
+ if !enabled {
+ return func() {}
+ }
+ exe, err := os.Executable()
+ if err != nil {
+ return func() {}
+ }
+ uiPath := filepath.Join(filepath.Dir(exe), "CopySync.exe")
+ if _, err := os.Stat(uiPath); err != nil {
+ return func() {} // 单独运行源码构建的 daemon,没有可打开的界面
+ }
+ trayCtx, cancel := context.WithCancel(ctx)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ if err := runTray(trayCtx, uiPath, quit); err != nil {
+ slog.Warn("启动托盘图标失败", "err", err)
+ }
+ }()
+ return func() {
+ cancel()
+ <-done // 删除图标后再退出进程,避免残留无响应的图标
+ }
+}
+
+func runTray(ctx context.Context, uiPath string, quit context.CancelFunc) error {
+ class, _ := windows.UTF16PtrFromString("CopySyncTrayWindow")
+ instance, _, _ := trayGetModule.Call(0)
+ wc := trayWindowClass{Size: uint32(unsafe.Sizeof(trayWindowClass{})), WndProc: trayCallback,
+ Instance: instance, ClassName: class}
+ if r, _, err := trayRegisterClass.Call(uintptr(unsafe.Pointer(&wc))); r == 0 {
+ return fmt.Errorf("注册托盘窗口: %w", err)
+ }
+ defer trayUnregisterClass.Call(uintptr(unsafe.Pointer(class)), instance)
+ t := &windowsTray{uiPath: uiPath, quit: quit}
+ activeTray = t
+ defer func() { activeTray = nil }()
+ title, _ := windows.UTF16PtrFromString("CopySync Tray")
+ hwnd, _, err := trayCreateWindow.Call(0, uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(title)),
+ 0, 0, 0, 0, 0, 0, 0, instance, 0)
+ if hwnd == 0 {
+ return fmt.Errorf("创建托盘窗口: %w", err)
+ }
+ defer trayDestroyWindow.Call(hwnd)
+ t.data = trayNotifyData{Size: uint32(unsafe.Sizeof(trayNotifyData{})), Window: hwnd,
+ ID: 1, Flags: 1 | 2 | 4 | 0x20 | 0x80, Callback: trayCallbackMessage,
+ // NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_GUID | NIF_SHOWTIP。
+ // 稳定 GUID 保留用户的托盘显示偏好,也能清掉崩溃前遗留的图标。
+ GUID: windows.GUID{Data1: 0x33e590c2, Data2: 0x9bfd, Data3: 0x47a3,
+ Data4: [8]byte{0xae, 0x76, 0x84, 0x2b, 0xef, 0xa2, 0xf6, 0xca}}}
+ tip, _ := windows.UTF16FromString("CopySync · 后台同步正在运行")
+ copy(t.data.Tip[:], tip)
+ path, _ := windows.UTF16PtrFromString(uiPath)
+ trayExtractIcon.Call(uintptr(unsafe.Pointer(path)), 0, 0, uintptr(unsafe.Pointer(&t.data.Icon)), 1)
+ if t.data.Icon != 0 {
+ defer trayDestroyIcon.Call(t.data.Icon)
+ } else {
+ t.data.Icon, _, _ = trayLoadIcon.Call(0, 32512) // IDI_APPLICATION(共享句柄)
+ }
+ message, _ := windows.UTF16PtrFromString("TaskbarCreated")
+ t.taskbarCreated, _, _ = trayRegisterMessage.Call(uintptr(unsafe.Pointer(message)))
+ // 异常退出时 Explorer 可能留有旧图标,用同一 GUID 删除后再注册。
+ trayNotify.Call(2, uintptr(unsafe.Pointer(&t.data))) // NIM_DELETE
+ t.addIcon()
+ defer trayNotify.Call(2, uintptr(unsafe.Pointer(&t.data)))
+
+ loopDone := make(chan struct{})
+ defer close(loopDone)
+ go func() {
+ select {
+ case <-ctx.Done():
+ trayPostMessage.Call(hwnd, trayWMClose, 0, 0)
+ case <-loopDone:
+ }
+ }()
+ var m trayMessage
+ for {
+ r, _, err := trayGetMessage.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
+ if int32(r) == -1 {
+ return fmt.Errorf("读取托盘消息: %w", err)
+ }
+ if r == 0 {
+ return nil
+ }
+ trayTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
+ trayDispatchMessage.Call(uintptr(unsafe.Pointer(&m)))
+ }
+}
+
+func (t *windowsTray) addIcon() {
+ if r, _, _ := trayNotify.Call(0, uintptr(unsafe.Pointer(&t.data))); r == 0 {
+ // 重复通知时可能已经存在,先尝试更新;登录时 Explorer 尚未就绪则稍后重试。
+ if r, _, _ := trayNotify.Call(1, uintptr(unsafe.Pointer(&t.data))); r == 0 {
+ traySetTimer.Call(t.data.Window, 1, 2000, 0)
+ return
+ }
+ }
+ t.data.Version = 4
+ trayNotify.Call(4, uintptr(unsafe.Pointer(&t.data))) // NIM_SETVERSION
+ trayKillTimer.Call(t.data.Window, 1)
+}
+
+func (t *windowsTray) openUI() {
+ cmd := exec.Command(t.uiPath)
+ if err := cmd.Start(); err != nil {
+ slog.Warn("从托盘打开界面失败", "err", err)
+ return
+ }
+ go cmd.Wait()
+}
+
+func (t *windowsTray) showMenu() {
+ menu, _, _ := trayCreateMenu.Call()
+ if menu == 0 {
+ return
+ }
+ defer trayDestroyMenu.Call(menu)
+ open, _ := windows.UTF16PtrFromString("打开 CopySync")
+ exit, _ := windows.UTF16PtrFromString("退出 CopySync")
+ trayAppendMenu.Call(menu, 0, trayOpenCommand, uintptr(unsafe.Pointer(open)))
+ trayAppendMenu.Call(menu, 0x800, 0, 0) // MF_SEPARATOR
+ trayAppendMenu.Call(menu, 0, trayQuitCommand, uintptr(unsafe.Pointer(exit)))
+ var point struct{ X, Y int32 }
+ trayGetCursorPos.Call(uintptr(unsafe.Pointer(&point)))
+ traySetForeground.Call(t.data.Window)
+ // TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON。
+ command, _, _ := trayTrackMenu.Call(menu, 0x100|0x80|2, uintptr(point.X), uintptr(point.Y), 0, t.data.Window, 0)
+ trayPostMessage.Call(t.data.Window, 0, 0, 0) // WM_NULL:点击菜单外部后正确收起
+ switch command {
+ case trayOpenCommand:
+ t.openUI()
+ case trayQuitCommand:
+ class, _ := windows.UTF16PtrFromString("FLUTTER_RUNNER_WIN32_WINDOW")
+ title, _ := windows.UTF16PtrFromString("CopySync")
+ if hwnd, _, _ := trayFindWindow.Call(uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(title))); hwnd != 0 {
+ trayPostMessage.Call(hwnd, trayWMClose, 0, 0)
+ }
+ t.quit() // 正常退出码 0:守护进程也退出,不会误当成崩溃再拉起
+ }
+}
+
+func trayWindowProc(hwnd, message, wparam, lparam uintptr) uintptr {
+ t := activeTray
+ if t != nil {
+ if t.taskbarCreated != 0 && message == t.taskbarCreated {
+ t.addIcon()
+ return 0
+ }
+ switch message {
+ case trayCallbackMessage:
+ switch lparam & 0xffff { // NOTIFYICON_VERSION_4:事件在低 16 位
+ case 0x400, 0x401, 0x203: // NIN_SELECT、NIN_KEYSELECT、WM_LBUTTONDBLCLK
+ t.openUI()
+ case 0x7b: // WM_CONTEXTMENU
+ t.showMenu()
+ }
+ return 0
+ case trayWMTimer:
+ t.addIcon()
+ return 0
+ case trayWMClose:
+ trayDestroyWindow.Call(hwnd)
+ return 0
+ case trayWMDestroy:
+ trayPostQuitMessage.Call(0)
+ return 0
+ }
+ }
+ r, _, _ := trayDefWindowProc.Call(hwnd, message, wparam, lparam)
+ return r
+}
diff --git a/client-core/internal/clipboard/windows.go b/client-core/internal/clipboard/windows.go
index a5ef296..d4d9a81 100644
--- a/client-core/internal/clipboard/windows.go
+++ b/client-core/internal/clipboard/windows.go
@@ -32,6 +32,7 @@ var (
procCloseClipboard = user32.NewProc("CloseClipboard")
procEmptyClipboard = user32.NewProc("EmptyClipboard")
procGetClipboardData = user32.NewProc("GetClipboardData")
+ procEnumClipboardFormats = user32.NewProc("EnumClipboardFormats")
procSetClipboardData = user32.NewProc("SetClipboardData")
procIsClipboardFormatAvailable = user32.NewProc("IsClipboardFormatAvailable")
procRegisterClipboardFormatW = user32.NewProc("RegisterClipboardFormatW")
@@ -366,8 +367,22 @@ func readImage() ([]byte, error) {
return b, nil
}
}
+ // Windows 枚举时先返回应用提供的格式,再返回由它合成的格式。
+ // 保留这个顺序:系统把普通 CF_DIB 转成 CF_DIBV5 时可能保留多余的
+ // 颜色掩码,导致像素偏移;而原生 CF_DIBV5 应优先读取,以保留透明度。
+ bitmapFormats := []uint32{cfDIBV5, cfDIB}
+ for f := uintptr(0); ; {
+ f, _, _ = procEnumClipboardFormats.Call(f)
+ if f == 0 || f == cfDIBV5 {
+ break
+ }
+ if f == cfDIB {
+ bitmapFormats = []uint32{cfDIB, cfDIBV5}
+ break
+ }
+ }
var lastErr error
- for _, f := range []uint32{cfDIBV5, cfDIB} {
+ for _, f := range bitmapFormats {
b, err := getData(f)
if err != nil {
lastErr = err
diff --git a/client-core/internal/clipboard/windows_test.go b/client-core/internal/clipboard/windows_test.go
index 250bf25..f2847f4 100644
--- a/client-core/internal/clipboard/windows_test.go
+++ b/client-core/internal/clipboard/windows_test.go
@@ -125,6 +125,53 @@ func TestWindowsImage(t *testing.T) {
}
}
+// 不提供 PNG,覆盖 Windows 为普通位图自动合成其他格式的路径。
+// 固定优先读取 CF_DIBV5 会读到系统从 CF_DIB 转换出的错位像素。
+func TestWindowsNativeBitmap(t *testing.T) {
+ for _, format := range []uint32{cfDIB, cfDIBV5} {
+ t.Run(map[uint32]string{cfDIB: "DIB", cfDIBV5: "DIBV5"}[format], func(t *testing.T) {
+ src := image.NewNRGBA(image.Rect(0, 0, 16, 16))
+ for y := range 16 {
+ for x := range 16 {
+ a := uint8(255)
+ if format == cfDIBV5 && x >= 8 {
+ a = 128
+ }
+ src.SetNRGBA(x, y, color.NRGBA{uint8(x * 17), uint8(y * 17), uint8((x + y) * 8), a})
+ }
+ }
+ data := imageToDIBV5(src)
+ if format == cfDIB {
+ data = dib(16, 16, 32, biBitfields, data[40:52], data[124:])
+ }
+ onMain(t, func() (struct{}, error) {
+ if err := openClipboard(); err != nil {
+ return struct{}{}, err
+ }
+ defer procCloseClipboard.Call()
+ procEmptyClipboard.Call()
+ return struct{}{}, setData(format, data)
+ })
+ got := onMain(t, New().Read)
+ img, err := png.Decode(bytes.NewReader(got.Image))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if img.Bounds() != src.Bounds() {
+ t.Fatalf("图片尺寸 = %v,应为 %v", img.Bounds(), src.Bounds())
+ }
+ for y := range 16 {
+ for x := range 16 {
+ want := src.NRGBAAt(x, y)
+ if c := color.NRGBAModel.Convert(img.At(x, y)); c != want {
+ t.Fatalf("(%d,%d) = %v,应为 %v", x, y, c, want)
+ }
+ }
+ }
+ })
+ }
+}
+
func TestWindowsFiles(t *testing.T) {
dir := t.TempDir()
var paths []string
diff --git a/client-core/internal/rpc/image_preview_test.go b/client-core/internal/rpc/image_preview_test.go
new file mode 100644
index 0000000..87acc29
--- /dev/null
+++ b/client-core/internal/rpc/image_preview_test.go
@@ -0,0 +1,59 @@
+package rpc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials/insecure"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+)
+
+func TestImagePreviewRPC(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ called := 0
+ s := NewServer(Deps{ImagePreviewPath: func(_ context.Context, id string) (string, error) {
+ called++
+ if id == "missing" {
+ return "", errors.New("图片已被清理")
+ }
+ return "/test/中文 图片.png", nil
+ }}, NewHub(), "test-token")
+ port, server, err := s.Serve(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer server.Stop()
+ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", port), grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ client := pb.NewDaemonServiceClient(conn)
+ requestCtx, requestCancel := context.WithTimeout(ctx, 5*time.Second)
+ defer requestCancel()
+ if _, err := client.GetImagePreview(requestCtx, &pb.GetImagePreviewRequest{ClipId: "image"}); status.Code(err) != codes.Unauthenticated {
+ t.Fatalf("unauthenticated: %v", err)
+ }
+ if called != 0 {
+ t.Fatal("unauthenticated call reached image resolver")
+ }
+ auth := metadata.AppendToOutgoingContext(requestCtx, tokenHeader, "test-token")
+ if _, err := client.GetImagePreview(auth, &pb.GetImagePreviewRequest{}); status.Code(err) != codes.InvalidArgument {
+ t.Fatalf("empty ID: %v", err)
+ }
+ if _, err := client.GetImagePreview(auth, &pb.GetImagePreviewRequest{ClipId: "missing"}); status.Code(err) != codes.FailedPrecondition {
+ t.Fatalf("missing image: %v", err)
+ }
+ got, err := client.GetImagePreview(auth, &pb.GetImagePreviewRequest{ClipId: "image"})
+ if err != nil || got.GetPath() != "/test/中文 图片.png" {
+ t.Fatalf("preview response: %v, %v", got, err)
+ }
+}
diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.go
index f5e747a..d28bf27 100644
--- a/client-core/internal/rpc/server.go
+++ b/client-core/internal/rpc/server.go
@@ -35,7 +35,9 @@ type Deps struct {
// 以下在对应里程碑接上,未实现时为 nil,方法返回 Unimplemented
Fetch func(ctx context.Context, clipID string) error
+ FetchForPreview func(ctx context.Context, clipID string) error
ApplyToClipboard func(ctx context.Context, clipID string) error
+ ImagePreviewPath func(ctx context.Context, clipID string) (string, error)
Permission func() clipboard.Permission
OpenPermissionSettings func() error
// Network 返回最近一轮网络出口探测的结果
@@ -205,10 +207,14 @@ func (s *Server) DeleteHistory(_ context.Context, req *pb.DeleteHistoryRequest)
}
func (s *Server) Fetch(ctx context.Context, req *pb.FetchRequest) (*pb.Empty, error) {
- if s.deps.Fetch == nil {
+ fetch := s.deps.Fetch
+ if req.GetPreserveClipboard() {
+ fetch = s.deps.FetchForPreview
+ }
+ if fetch == nil {
return nil, status.Error(codes.Unimplemented, "传输层尚未接入(M4)")
}
- if err := s.deps.Fetch(ctx, req.GetClipId()); err != nil {
+ if err := fetch(ctx, req.GetClipId()); err != nil {
return nil, status.Errorf(codes.Internal, "拉取失败: %v", err)
}
return &pb.Empty{}, nil
@@ -225,6 +231,21 @@ func (s *Server) ApplyToClipboard(ctx context.Context,
return &pb.Empty{}, nil
}
+func (s *Server) GetImagePreview(ctx context.Context,
+ req *pb.GetImagePreviewRequest) (*pb.GetImagePreviewResponse, error) {
+ if req.GetClipId() == "" {
+ return nil, status.Error(codes.InvalidArgument, "缺少图片记录 ID")
+ }
+ if s.deps.ImagePreviewPath == nil {
+ return nil, status.Error(codes.Unimplemented, "请更新后台服务后再预览图片")
+ }
+ path, err := s.deps.ImagePreviewPath(ctx, req.GetClipId())
+ if err != nil {
+ return nil, status.Error(codes.FailedPrecondition, err.Error())
+ }
+ return &pb.GetImagePreviewResponse{Path: path}, nil
+}
+
// ─────────────────────────── 配置与状态 ───────────────────────────
func (s *Server) GetConfig(context.Context, *pb.Empty) (*pb.Config, error) {
diff --git a/client-core/internal/sync/engine.go b/client-core/internal/sync/engine.go
index e460142..dd1009f 100644
--- a/client-core/internal/sync/engine.go
+++ b/client-core/internal/sync/engine.go
@@ -668,6 +668,15 @@ func (e *Engine) handleDone(d *pb.TransferDone) {
// Fetch 主动拉取一条仅有元数据的记录。
func (e *Engine) Fetch(ctx context.Context, clipID string) error {
+ return e.fetch(ctx, clipID, false)
+}
+
+// FetchForPreview 下载旧图片只用于查看,不能覆盖用户刚复制的内容。
+func (e *Engine) FetchForPreview(ctx context.Context, clipID string) error {
+ return e.fetch(ctx, clipID, true)
+}
+
+func (e *Engine) fetch(ctx context.Context, clipID string, preserveClipboard bool) error {
clip, err := e.store.GetClip(clipID)
if err != nil {
return err
@@ -675,6 +684,11 @@ func (e *Engine) Fetch(ctx context.Context, clipID string) error {
if clip.Outgoing {
return errors.New("这是本机复制的内容,无需拉取")
}
+ if preserveClipboard {
+ e.mu.Lock()
+ e.quiet[clipID] = true
+ e.mu.Unlock()
+ }
if err := e.send(clip.OriginDeviceID, &pb.PeerMessage{
Payload: &pb.PeerMessage_Fetch{Fetch: &pb.PeerFetch{ClipId: clipID}},
}); err != nil {
@@ -726,6 +740,29 @@ func (e *Engine) applyToClipboard(ctx context.Context, clip store.Clip) error {
return e.watcher.Write(ctx, content)
}
+// ImagePreviewPath 只解析本地图片位置,不拉取文件、不写剪贴板。
+func (e *Engine) ImagePreviewPath(_ context.Context, clipID string) (string, error) {
+ clip, err := e.store.GetClip(clipID)
+ if err != nil {
+ return "", errors.New("找不到这条图片记录")
+ }
+ if clip.Kind != store.KindImage {
+ return "", errors.New("这条记录不是图片")
+ }
+ if clip.Status != store.StatusReady {
+ return "", errors.New("图片尚未下载或已经过期")
+ }
+ paths, err := e.localPaths(clip)
+ if err != nil || len(paths) != 1 {
+ return "", errors.New("图片已不在本机,可能已被清理")
+ }
+ info, err := os.Stat(paths[0])
+ if err != nil || !info.Mode().IsRegular() {
+ return "", errors.New("图片文件不可用")
+ }
+ return paths[0], nil
+}
+
// localPaths 返回这条记录在本机可用的实际路径。
func (e *Engine) localPaths(clip store.Clip) ([]string, error) {
if clip.CachePath != "" && e.cache.Exists(clip.CachePath) {
diff --git a/client-core/internal/sync/image_preview_test.go b/client-core/internal/sync/image_preview_test.go
new file mode 100644
index 0000000..65ab42e
--- /dev/null
+++ b/client-core/internal/sync/image_preview_test.go
@@ -0,0 +1,120 @@
+package sync
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+ "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"
+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"
+)
+
+func TestImagePreviewPath(t *testing.T) {
+ root := t.TempDir()
+ db, err := store.Open(filepath.Join(root, "test.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ blobs, err := cache.New(filepath.Join(root, "cache"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 不设置 watcher:预览不能依赖或写入剪贴板。
+ e := &Engine{store: db, cache: blobs}
+ rel, dir, err := blobs.Dir("picture")
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "中文 图片.png")
+ if err := os.WriteFile(path, []byte("unchanged image bytes"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cases := []struct {
+ name string
+ clip store.Clip
+ want string
+ }{
+ {"received", store.Clip{Kind: store.KindImage, Status: store.StatusReady, CachePath: rel}, path},
+ {"outgoing", store.Clip{Kind: store.KindImage, Status: store.StatusReady, SourcePaths: []string{path}}, path},
+ {"remote-only", store.Clip{Kind: store.KindImage, Status: store.StatusRemoteOnly, SourcePaths: []string{path}}, ""},
+ {"expired", store.Clip{Kind: store.KindImage, Status: store.StatusExpired, SourcePaths: []string{path}}, ""},
+ {"not-image", store.Clip{Kind: store.KindFile, Status: store.StatusReady, SourcePaths: []string{path}}, ""},
+ {"deleted-file", store.Clip{Kind: store.KindImage, Status: store.StatusReady, SourcePaths: []string{filepath.Join(root, "absent.png")}}, ""},
+ {"directory", store.Clip{Kind: store.KindImage, Status: store.StatusReady, SourcePaths: []string{dir}}, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ tc.clip.ID = tc.name
+ if err := db.PutClip(tc.clip); err != nil {
+ t.Fatal(err)
+ }
+ got, err := e.ImagePreviewPath(context.Background(), tc.name)
+ if tc.want == "" {
+ if err == nil {
+ t.Fatalf("unexpected path: %s", got)
+ }
+ } else if err != nil || got != tc.want {
+ t.Fatalf("got %q, %v; want %q", got, err, tc.want)
+ }
+ })
+ }
+ if _, err := e.ImagePreviewPath(context.Background(), "missing-record"); err == nil {
+ t.Fatal("missing record accepted")
+ }
+ if data, err := os.ReadFile(path); err != nil || string(data) != "unchanged image bytes" {
+ t.Fatal("preview changed image")
+ }
+}
+
+func TestPreviewDownloadDoesNotApplyClipboard(t *testing.T) {
+ root := t.TempDir()
+ db, err := store.Open(filepath.Join(root, "test.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { db.Close() })
+ blobs, err := cache.New(filepath.Join(root, "cache"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ clip := store.Clip{ID: "preview", Kind: store.KindImage, Status: store.StatusRemoteOnly, OriginDeviceID: "peer"}
+ if err := db.PutClip(clip); err != nil {
+ t.Fatal(err)
+ }
+ sent := false
+ e := New(Options{Store: db, Cache: blobs,
+ LoadConfig: func() config.Config { return config.Default() },
+ Send: func(peer string, message *pb.PeerMessage) error {
+ sent = peer == "peer" && message.GetFetch().GetClipId() == "preview"
+ return nil
+ },
+ })
+ if err := e.FetchForPreview(context.Background(), clip.ID); err != nil {
+ t.Fatal(err)
+ }
+ if !sent {
+ t.Fatal("download was not requested")
+ }
+ rel, dir, err := blobs.Dir(clip.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "image.png")
+ if err := os.WriteFile(path, []byte("downloaded image"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ // 默认 AutoApplyToClipboard=true 且 watcher=nil:误写剪贴板会直接导致测试失败。
+ e.finishReceive(&receiver{clipID: clip.ID, streamID: "test-stream", from: "peer", start: time.Now()}, rel, []string{path})
+ got, err := e.ImagePreviewPath(context.Background(), clip.ID)
+ if err != nil || got != path {
+ t.Fatalf("downloaded preview: %q, %v", got, err)
+ }
+ if e.quiet[clip.ID] {
+ t.Fatal("completed preview download left quiet state")
+ }
+}
diff --git a/design/windows-client.md b/design/windows-client.md
index 36b856a..71c50ff 100644
--- a/design/windows-client.md
+++ b/design/windows-client.md
@@ -9,7 +9,7 @@
让 Windows 电脑加入 CopySync:与 Mac、与其他 Windows 电脑互相同步文本、带格式文本、图片和文件,体验与 Mac 版一致。
- 在一台上 `Ctrl+C`,另一台上 `Ctrl+V`(或 `⌘V`)。粘贴文件时得到的是真实文件,可以直接粘贴进资源管理器、微信、Office。
-- 开机自启,关掉窗口照常同步,崩溃自动拉起。
+- 开机自启,关掉窗口照常同步,崩溃自动拉起。Windows 安装时创建桌面快捷方式;后台服务持有托盘图标,点击可打开界面,右键可打开界面或退出 CopySync。
- 网络行为与 Mac 版完全相同:直连优先、多出口打洞、自动中转、端到端加密。
- 与 Mac 版互通,Mac 端不升级也能和 Windows 配对、同步(协议不变)。
@@ -18,7 +18,6 @@
| 不做 | 原因 | 何时 |
|---|---|---|
| ARM64 原生包 | Flutter 3.47 才正式支持 Windows ARM64,且只能在 ARM 机器上构建;x64 版在 ARM 上可以模拟运行 | 二期,用 GitHub 的 ARM Windows 构建机 |
-| 托盘图标 | Mac 版也没有;后台服务本身不带界面 | 二期 |
| 虚拟文件(Outlook 附件、压缩包里直接复制的文件) | 剪贴板里没有真实路径,只有流,需要实现 COM 接口 | 视需求 |
| 自动更新、微软商店 | 先跑通分发与签名 | 二期 |
@@ -266,7 +265,7 @@ M1 结束时就能验证最大的不确定点:剪贴板方案、防火墙行
## 十三、需要拍板的事
1. **代码签名**:一期不签名(推荐,先验证需求),还是一开始就买证书?
-2. **托盘图标**:一期不做(推荐,与 Mac 版一致),还是 Windows 用户更习惯有托盘、一期就做?
+2. **托盘图标**:已按用户需求加入一期,由后台服务持有,随登录自启、关闭主窗口后保留;退出时停止当前后台同步,但保留下次登录的自启设置。
3. **ARM64**:一期只出 x64(推荐,ARM 机器可以模拟运行),还是同时出 ARM64?
4. **Mac 版的敏感内容漏洞**(第四节第 3 条):建议马上单独修,发 1.1.3。
diff --git a/design/windows-validation-2026-10-09.md b/design/windows-validation-2026-10-09.md
new file mode 100644
index 0000000..de8716d
--- /dev/null
+++ b/design/windows-validation-2026-10-09.md
@@ -0,0 +1,69 @@
+# Windows 实机验证记录(2026-10-09)
+
+状态:本轮验证完成;发现一处位图读取问题,已修复并复测通过。
+
+环境:Parallels 的 `window` 虚拟机,Windows 11 build 26200,x64,登录用户的交互式桌面。
+基线:`windows` 分支 `7d82b45bef2d7b7c04c397bf016237be60ba1027`,CI run `37825616287`,安装包版本 `1.1.2`。
+
+## 测试隔离
+
+- Parallels 共享剪贴板已手动关闭,并用 `prlctl list -i window` 确认。
+- Windows 测试期间,用户刚建立的设备身份、数据和配对关系完整移至备份目录,测试使用全新身份。
+- Mac 使用 `-tags fakeclip` 编译的测试 daemon,独立数据目录、设备身份与 `copy.json` / `pasted.json`,没有操作 Mac 系统剪贴板。
+- 信令服务仅监听 Parallels 主机网卡的独立端口,两个测试身份通过局域网 P2P 直连。
+
+## 已验证
+
+| 项目 | 结果与证据 |
+|---|---|
+| 普通用户安装 | 安装器退出码 0,安装到当前用户目录,卸载注册正常,无需重启 |
+| 图形界面启动 | 正常显示启用后台同步的引导页,进程响应正常 |
+| 界面单实例 | 再次启动后仍只有一个界面进程,原 PID 保留 |
+| 界面启用后台同步 | 实际点击按钮后创建 HKCU Run 项;守护进程与 daemon 均运行在用户会话内 |
+| 关闭界面 | 后台进程继续运行,测试设备仍直连并能同步 |
+| Windows 剪贴板集成测试 | 文本、HTML、PNG、文件列表、富文本判型、敏感标记、变化通知全部通过,无跳过 |
+| Mac → Windows 文本/HTML | 中文、emoji、多行文本一致,HTML 与纯文本后备内容一致 |
+| Mac → Windows 图片 | 透明 PNG 原始字节一致 |
+| Mac → Windows 文件 | 文件内容 SHA-256 一致;中文、空格保留,半角冒号转全角冒号,未创建 NTFS 备用数据流 |
+| Windows → Mac 文本/HTML | 中文、emoji、CRLF → LF、CF_HTML 的 UTF-8 字节偏移处理正确 |
+| Windows → Mac 文件 | 中文/全角冒号文件名及内容逐字节一致 |
+| Windows → Mac 普通位图 | 原包失败;修复后 16×16 图片全部像素一致,见下方问题记录 |
+| daemon 单实例 | 重复 daemon 退出码 3,重复守护进程退出码 0;始终只有一个守护进程和一个工作进程 |
+| 崩溃恢复 | 强制终止工作进程后约 0.32 秒重新拉起,重新连接对端;此次进程已运行超过 10 秒的限速窗口 |
+| 覆盖安装 | 修复包覆盖安装成功,安装器自动重启后台服务,原测试身份与配对关系保留,安装后程序哈希与修复产物一致 |
+| 重启后登录自启 | 正常重启 Windows 后,用户登录即自动启动守护进程与 daemon;当时 GUI 未运行,已恢复测试设备直连 |
+| 卸载 | 静默卸载成功;界面/后台进程、程序文件、Run 项与卸载注册均已清理;默认保留数据库和设备身份,身份文件哈希不变 |
+| 卸载后重装 | 安装成功,未擅自启用后台服务;手动启动服务后,测试身份与配对关系仍在 |
+| 原使用环境恢复 | Windows 原身份文件哈希一致,原数据与自启命令恢复,安装修复版本后与原 Mac 重新直连;临时测试服务和编译器已停止/卸载 |
+
+安装修复包并重启登录后,再次完成双向文本、HTML、图片、文件八项测试,全部通过;Windows 原生位图逐像素一致。卸载、重装和原使用环境恢复也已完成。
+
+## 发现并修复的问题
+
+`readImage` 固定先请求 `CF_DIBV5`。当 Windows 从普通 `CF_DIB` / `CF_BITMAP` 自动合成该格式时,实测在 124 字节头部之后仍留有 12 字节颜色掩码;读取方把它当成像素,图片整体错位。
+
+复现:用 Windows Forms 把 16×16 彩色位图放入系统剪贴板,通过正式安装的 daemon 传至 Mac 测试实例。源图 `(0,0)` 为 `{0,0,0,255}`,收到 `{221,17,112,255}`。Windows 原生读取该源图像素正确,证明问题位于 CopySync 的格式选择。原有 PNG 往返测试绕过了此路径。
+
+修复:PNG 仍优先;其余位图遵循 `EnumClipboardFormats` 的顺序,优先读取原生格式,再尝试系统合成格式。保留原生 DIBV5 的透明度,不猜测内存偏移。
+
+新增 `TestWindowsNativeBitmap`,覆盖无 PNG 后备的普通 DIB 和带透明度的原生 DIBV5。虚拟机上旧实现的 DIB 子用例失败,新实现两个子用例均通过,随后原生 Windows Forms 位图的端到端逐像素比较通过。
+
+代码检查:Mac 的 `go test ./internal/clipboard ./internal/pack`,Windows 目标的 `go vet ./internal/clipboard ./cmd/copysyncd`,以及虚拟机内完整 Windows 剪贴板测试全部通过。
+
+## 结束状态
+
+- Windows 已恢复用户原有的数据、身份、配对关系和自启项,正在运行修复后的客户端,并与原 Mac 直连。
+- Mac 原生产 daemon 的 PID 始终为 10576,未重启或改动;Mac 测试 daemon 和测试信令服务已退出。
+- Parallels 共享剪贴板保持关闭,避免与 CopySync 同时转发内容。此设置需由用户手动调整。
+- 测试数据归档保留在虚拟机 `C:\CopySyncValidation-20261009\test-data-completed`,可用于复现;原用户数据已移回正常目录。
+- 修改留在 `windows` 分支工作区,未提交、推送或发布。
+
+## 安装包与证据
+
+修复包基于原 CI 的 Flutter 界面和 CLI,仅替换由当前工作区编译的 Windows daemon,使用仓库原有 Inno Setup 脚本重新打包。版本仍为 1.1.2,属于本地验证产物,未发布;发布前需由包含此修复的提交重新运行 CI。
+
+- 修复安装包 SHA-256:`8e9d690dd16675330e2b6f2c6fdb1a1e99387c650851b1431e36f0fa62b782a1`
+- 修复便携包 SHA-256:`479235d1cc0ecd35114a263a33572db6d9fe02ef721d4eb794e82c57a636deee`
+- 本机证据目录:`~/Library/Caches/copysync-validation-20261009/`,含安装日志、回归测试前后日志、同步断言、图片及脚本。
+
+本轮 Mac 端使用文件剪贴板测试适配器;Windows 端使用真实系统剪贴板。实际 Mac 系统剪贴板交互和公网中转不属于本轮测试范围。
diff --git a/proto/copysync/v1/daemon.proto b/proto/copysync/v1/daemon.proto
index b5d15a4..8c0ac31 100644
--- a/proto/copysync/v1/daemon.proto
+++ b/proto/copysync/v1/daemon.proto
@@ -20,6 +20,8 @@ service DaemonService {
rpc Fetch(FetchRequest) returns (Empty);
// 把某条已就绪的记录重新放进本机剪贴板
rpc ApplyToClipboard(ApplyToClipboardRequest) returns (Empty);
+ // 只返回已就绪图片在本机的路径,不改动剪贴板,也不把路径发给对端。
+ rpc GetImagePreview(GetImagePreviewRequest) returns (GetImagePreviewResponse);
rpc ListDevices(Empty) returns (ListDevicesResponse);
rpc CreatePairingCode(Empty) returns (CreatePairingCodeResponse);
@@ -163,6 +165,7 @@ message DeleteHistoryRequest {
message FetchRequest {
string clip_id = 1;
+ bool preserve_clipboard = 2; // 预览下载:收完后不覆盖用户的剪贴板
}
message ApplyToClipboardRequest {
@@ -250,3 +253,11 @@ message Status {
int32 peers_online = 6;
string version = 7;
}
+
+message GetImagePreviewRequest {
+ string clip_id = 1;
+}
+
+message GetImagePreviewResponse {
+ string path = 1;
+}
diff --git a/proto/gen/copysync/v1/daemon.pb.go b/proto/gen/copysync/v1/daemon.pb.go
index 57d8d7e..016b4f5 100644
--- a/proto/gen/copysync/v1/daemon.pb.go
+++ b/proto/gen/copysync/v1/daemon.pb.go
@@ -1022,10 +1022,11 @@ func (x *DeleteHistoryRequest) GetAll() bool {
}
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
+ state protoimpl.MessageState `protogen:"open.v1"`
+ ClipId string `protobuf:"bytes,1,opt,name=clip_id,json=clipId,proto3" json:"clip_id,omitempty"`
+ PreserveClipboard bool `protobuf:"varint,2,opt,name=preserve_clipboard,json=preserveClipboard,proto3" json:"preserve_clipboard,omitempty"` // 预览下载:收完后不覆盖用户的剪贴板
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
}
func (x *FetchRequest) Reset() {
@@ -1065,6 +1066,13 @@ func (x *FetchRequest) GetClipId() string {
return ""
}
+func (x *FetchRequest) GetPreserveClipboard() bool {
+ if x != nil {
+ return x.PreserveClipboard
+ }
+ return false
+}
+
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"`
@@ -1779,6 +1787,94 @@ func (x *Status) GetVersion() string {
return ""
}
+type GetImagePreviewRequest 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 *GetImagePreviewRequest) Reset() {
+ *x = GetImagePreviewRequest{}
+ mi := &file_copysync_v1_daemon_proto_msgTypes[22]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetImagePreviewRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetImagePreviewRequest) ProtoMessage() {}
+
+func (x *GetImagePreviewRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_copysync_v1_daemon_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 GetImagePreviewRequest.ProtoReflect.Descriptor instead.
+func (*GetImagePreviewRequest) Descriptor() ([]byte, []int) {
+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{22}
+}
+
+func (x *GetImagePreviewRequest) GetClipId() string {
+ if x != nil {
+ return x.ClipId
+ }
+ return ""
+}
+
+type GetImagePreviewResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetImagePreviewResponse) Reset() {
+ *x = GetImagePreviewResponse{}
+ mi := &file_copysync_v1_daemon_proto_msgTypes[23]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetImagePreviewResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetImagePreviewResponse) ProtoMessage() {}
+
+func (x *GetImagePreviewResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_copysync_v1_daemon_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 GetImagePreviewResponse.ProtoReflect.Descriptor instead.
+func (*GetImagePreviewResponse) Descriptor() ([]byte, []int) {
+ return file_copysync_v1_daemon_proto_rawDescGZIP(), []int{23}
+}
+
+func (x *GetImagePreviewResponse) GetPath() string {
+ if x != nil {
+ return x.Path
+ }
+ return ""
+}
+
var File_copysync_v1_daemon_proto protoreflect.FileDescriptor
const file_copysync_v1_daemon_proto_rawDesc = "" +
@@ -1845,9 +1941,10 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +
"\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" +
+ "\x03all\x18\x02 \x01(\bR\x03all\"V\n" +
"\fFetchRequest\x12\x17\n" +
- "\aclip_id\x18\x01 \x01(\tR\x06clipId\"2\n" +
+ "\aclip_id\x18\x01 \x01(\tR\x06clipId\x12-\n" +
+ "\x12preserve_clipboard\x18\x02 \x01(\bR\x11preserveClipboard\"2\n" +
"\x17ApplyToClipboardRequest\x12\x17\n" +
"\aclip_id\x18\x01 \x01(\tR\x06clipId\"i\n" +
"\x13ListDevicesResponse\x12'\n" +
@@ -1902,7 +1999,11 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +
"\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" +
+ "\aversion\x18\a \x01(\tR\aversion\"1\n" +
+ "\x16GetImagePreviewRequest\x12\x17\n" +
+ "\aclip_id\x18\x01 \x01(\tR\x06clipId\"-\n" +
+ "\x17GetImagePreviewResponse\x12\x12\n" +
+ "\x04path\x18\x01 \x01(\tR\x04path*v\n" +
"\bClipKind\x12\x19\n" +
"\x15CLIP_KIND_UNSPECIFIED\x10\x00\x12\x12\n" +
"\x0eCLIP_KIND_TEXT\x10\x01\x12\x12\n" +
@@ -1928,13 +2029,14 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +
"\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\x97\b\n" +
+ " CLIPBOARD_PERMISSION_ALWAYS_DENY\x10\x052\xf5\b\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" +
+ "\x10ApplyToClipboard\x12$.copysync.v1.ApplyToClipboardRequest\x1a\x12.copysync.v1.Empty\x12\\\n" +
+ "\x0fGetImagePreview\x12#.copysync.v1.GetImagePreviewRequest\x1a$.copysync.v1.GetImagePreviewResponse\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" +
@@ -1960,7 +2062,7 @@ func file_copysync_v1_daemon_proto_rawDescGZIP() []byte {
}
var file_copysync_v1_daemon_proto_enumTypes = make([]protoimpl.EnumInfo, 4)
-var file_copysync_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 22)
+var file_copysync_v1_daemon_proto_msgTypes = make([]protoimpl.MessageInfo, 24)
var file_copysync_v1_daemon_proto_goTypes = []any{
(ClipKind)(0), // 0: copysync.v1.ClipKind
(ClipStatus)(0), // 1: copysync.v1.ClipStatus
@@ -1988,6 +2090,8 @@ var file_copysync_v1_daemon_proto_goTypes = []any{
(*NetworkInfo)(nil), // 23: copysync.v1.NetworkInfo
(*NetworkEgress)(nil), // 24: copysync.v1.NetworkEgress
(*Status)(nil), // 25: copysync.v1.Status
+ (*GetImagePreviewRequest)(nil), // 26: copysync.v1.GetImagePreviewRequest
+ (*GetImagePreviewResponse)(nil), // 27: copysync.v1.GetImagePreviewResponse
}
var file_copysync_v1_daemon_proto_depIdxs = []int32{
0, // 0: copysync.v1.ClipRecord.kind:type_name -> copysync.v1.ClipKind
@@ -2012,33 +2116,35 @@ var file_copysync_v1_daemon_proto_depIdxs = []int32{
13, // 19: copysync.v1.DaemonService.DeleteHistory:input_type -> copysync.v1.DeleteHistoryRequest
14, // 20: copysync.v1.DaemonService.Fetch:input_type -> copysync.v1.FetchRequest
15, // 21: copysync.v1.DaemonService.ApplyToClipboard:input_type -> copysync.v1.ApplyToClipboardRequest
- 4, // 22: copysync.v1.DaemonService.ListDevices:input_type -> copysync.v1.Empty
- 4, // 23: copysync.v1.DaemonService.CreatePairingCode:input_type -> copysync.v1.Empty
- 18, // 24: copysync.v1.DaemonService.RedeemPairingCode:input_type -> copysync.v1.RedeemPairingCodeRequest
- 20, // 25: copysync.v1.DaemonService.ConfirmPairing:input_type -> copysync.v1.ConfirmPairingRequest
- 21, // 26: copysync.v1.DaemonService.Unpair:input_type -> copysync.v1.UnpairRequest
- 4, // 27: copysync.v1.DaemonService.GetConfig:input_type -> copysync.v1.Empty
- 22, // 28: copysync.v1.DaemonService.UpdateConfig:input_type -> copysync.v1.Config
- 4, // 29: copysync.v1.DaemonService.GetStatus:input_type -> copysync.v1.Empty
- 4, // 30: copysync.v1.DaemonService.RequestClipboardPermission:input_type -> copysync.v1.Empty
- 4, // 31: copysync.v1.DaemonService.GetNetwork:input_type -> copysync.v1.Empty
- 10, // 32: copysync.v1.DaemonService.Subscribe:output_type -> copysync.v1.Event
- 12, // 33: copysync.v1.DaemonService.ListHistory:output_type -> copysync.v1.ListHistoryResponse
- 4, // 34: copysync.v1.DaemonService.DeleteHistory:output_type -> copysync.v1.Empty
- 4, // 35: copysync.v1.DaemonService.Fetch:output_type -> copysync.v1.Empty
- 4, // 36: copysync.v1.DaemonService.ApplyToClipboard:output_type -> copysync.v1.Empty
- 16, // 37: copysync.v1.DaemonService.ListDevices:output_type -> copysync.v1.ListDevicesResponse
- 17, // 38: copysync.v1.DaemonService.CreatePairingCode:output_type -> copysync.v1.CreatePairingCodeResponse
- 19, // 39: copysync.v1.DaemonService.RedeemPairingCode:output_type -> copysync.v1.RedeemPairingCodeResponse
- 4, // 40: copysync.v1.DaemonService.ConfirmPairing:output_type -> copysync.v1.Empty
- 4, // 41: copysync.v1.DaemonService.Unpair:output_type -> copysync.v1.Empty
- 22, // 42: copysync.v1.DaemonService.GetConfig:output_type -> copysync.v1.Config
- 22, // 43: copysync.v1.DaemonService.UpdateConfig:output_type -> copysync.v1.Config
- 25, // 44: copysync.v1.DaemonService.GetStatus:output_type -> copysync.v1.Status
- 4, // 45: copysync.v1.DaemonService.RequestClipboardPermission:output_type -> copysync.v1.Empty
- 23, // 46: copysync.v1.DaemonService.GetNetwork:output_type -> copysync.v1.NetworkInfo
- 32, // [32:47] is the sub-list for method output_type
- 17, // [17:32] is the sub-list for method input_type
+ 26, // 22: copysync.v1.DaemonService.GetImagePreview:input_type -> copysync.v1.GetImagePreviewRequest
+ 4, // 23: copysync.v1.DaemonService.ListDevices:input_type -> copysync.v1.Empty
+ 4, // 24: copysync.v1.DaemonService.CreatePairingCode:input_type -> copysync.v1.Empty
+ 18, // 25: copysync.v1.DaemonService.RedeemPairingCode:input_type -> copysync.v1.RedeemPairingCodeRequest
+ 20, // 26: copysync.v1.DaemonService.ConfirmPairing:input_type -> copysync.v1.ConfirmPairingRequest
+ 21, // 27: copysync.v1.DaemonService.Unpair:input_type -> copysync.v1.UnpairRequest
+ 4, // 28: copysync.v1.DaemonService.GetConfig:input_type -> copysync.v1.Empty
+ 22, // 29: copysync.v1.DaemonService.UpdateConfig:input_type -> copysync.v1.Config
+ 4, // 30: copysync.v1.DaemonService.GetStatus:input_type -> copysync.v1.Empty
+ 4, // 31: copysync.v1.DaemonService.RequestClipboardPermission:input_type -> copysync.v1.Empty
+ 4, // 32: copysync.v1.DaemonService.GetNetwork:input_type -> copysync.v1.Empty
+ 10, // 33: copysync.v1.DaemonService.Subscribe:output_type -> copysync.v1.Event
+ 12, // 34: copysync.v1.DaemonService.ListHistory:output_type -> copysync.v1.ListHistoryResponse
+ 4, // 35: copysync.v1.DaemonService.DeleteHistory:output_type -> copysync.v1.Empty
+ 4, // 36: copysync.v1.DaemonService.Fetch:output_type -> copysync.v1.Empty
+ 4, // 37: copysync.v1.DaemonService.ApplyToClipboard:output_type -> copysync.v1.Empty
+ 27, // 38: copysync.v1.DaemonService.GetImagePreview:output_type -> copysync.v1.GetImagePreviewResponse
+ 16, // 39: copysync.v1.DaemonService.ListDevices:output_type -> copysync.v1.ListDevicesResponse
+ 17, // 40: copysync.v1.DaemonService.CreatePairingCode:output_type -> copysync.v1.CreatePairingCodeResponse
+ 19, // 41: copysync.v1.DaemonService.RedeemPairingCode:output_type -> copysync.v1.RedeemPairingCodeResponse
+ 4, // 42: copysync.v1.DaemonService.ConfirmPairing:output_type -> copysync.v1.Empty
+ 4, // 43: copysync.v1.DaemonService.Unpair:output_type -> copysync.v1.Empty
+ 22, // 44: copysync.v1.DaemonService.GetConfig:output_type -> copysync.v1.Config
+ 22, // 45: copysync.v1.DaemonService.UpdateConfig:output_type -> copysync.v1.Config
+ 25, // 46: copysync.v1.DaemonService.GetStatus:output_type -> copysync.v1.Status
+ 4, // 47: copysync.v1.DaemonService.RequestClipboardPermission:output_type -> copysync.v1.Empty
+ 23, // 48: copysync.v1.DaemonService.GetNetwork:output_type -> copysync.v1.NetworkInfo
+ 33, // [33:49] is the sub-list for method output_type
+ 17, // [17:33] is the sub-list for method input_type
17, // [17:17] is the sub-list for extension type_name
17, // [17:17] is the sub-list for extension extendee
0, // [0:17] is the sub-list for field type_name
@@ -2064,7 +2170,7 @@ func file_copysync_v1_daemon_proto_init() {
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: 22,
+ NumMessages: 24,
NumExtensions: 0,
NumServices: 1,
},
diff --git a/proto/gen/copysync/v1/daemon_grpc.pb.go b/proto/gen/copysync/v1/daemon_grpc.pb.go
index d67521e..5511589 100644
--- a/proto/gen/copysync/v1/daemon_grpc.pb.go
+++ b/proto/gen/copysync/v1/daemon_grpc.pb.go
@@ -29,6 +29,7 @@ const (
DaemonService_DeleteHistory_FullMethodName = "/copysync.v1.DaemonService/DeleteHistory"
DaemonService_Fetch_FullMethodName = "/copysync.v1.DaemonService/Fetch"
DaemonService_ApplyToClipboard_FullMethodName = "/copysync.v1.DaemonService/ApplyToClipboard"
+ DaemonService_GetImagePreview_FullMethodName = "/copysync.v1.DaemonService/GetImagePreview"
DaemonService_ListDevices_FullMethodName = "/copysync.v1.DaemonService/ListDevices"
DaemonService_CreatePairingCode_FullMethodName = "/copysync.v1.DaemonService/CreatePairingCode"
DaemonService_RedeemPairingCode_FullMethodName = "/copysync.v1.DaemonService/RedeemPairingCode"
@@ -53,6 +54,8 @@ type DaemonServiceClient interface {
Fetch(ctx context.Context, in *FetchRequest, opts ...grpc.CallOption) (*Empty, error)
// 把某条已就绪的记录重新放进本机剪贴板
ApplyToClipboard(ctx context.Context, in *ApplyToClipboardRequest, opts ...grpc.CallOption) (*Empty, error)
+ // 只返回已就绪图片在本机的路径,不改动剪贴板,也不把路径发给对端。
+ GetImagePreview(ctx context.Context, in *GetImagePreviewRequest, opts ...grpc.CallOption) (*GetImagePreviewResponse, 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)
@@ -135,6 +138,16 @@ func (c *daemonServiceClient) ApplyToClipboard(ctx context.Context, in *ApplyToC
return out, nil
}
+func (c *daemonServiceClient) GetImagePreview(ctx context.Context, in *GetImagePreviewRequest, opts ...grpc.CallOption) (*GetImagePreviewResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(GetImagePreviewResponse)
+ err := c.cc.Invoke(ctx, DaemonService_GetImagePreview_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)
@@ -247,6 +260,8 @@ type DaemonServiceServer interface {
Fetch(context.Context, *FetchRequest) (*Empty, error)
// 把某条已就绪的记录重新放进本机剪贴板
ApplyToClipboard(context.Context, *ApplyToClipboardRequest) (*Empty, error)
+ // 只返回已就绪图片在本机的路径,不改动剪贴板,也不把路径发给对端。
+ GetImagePreview(context.Context, *GetImagePreviewRequest) (*GetImagePreviewResponse, error)
ListDevices(context.Context, *Empty) (*ListDevicesResponse, error)
CreatePairingCode(context.Context, *Empty) (*CreatePairingCodeResponse, error)
RedeemPairingCode(context.Context, *RedeemPairingCodeRequest) (*RedeemPairingCodeResponse, error)
@@ -285,6 +300,9 @@ func (UnimplementedDaemonServiceServer) Fetch(context.Context, *FetchRequest) (*
func (UnimplementedDaemonServiceServer) ApplyToClipboard(context.Context, *ApplyToClipboardRequest) (*Empty, error) {
return nil, status.Error(codes.Unimplemented, "method ApplyToClipboard not implemented")
}
+func (UnimplementedDaemonServiceServer) GetImagePreview(context.Context, *GetImagePreviewRequest) (*GetImagePreviewResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetImagePreview not implemented")
+}
func (UnimplementedDaemonServiceServer) ListDevices(context.Context, *Empty) (*ListDevicesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListDevices not implemented")
}
@@ -419,6 +437,24 @@ func _DaemonService_ApplyToClipboard_Handler(srv interface{}, ctx context.Contex
return interceptor(ctx, in, info, handler)
}
+func _DaemonService_GetImagePreview_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetImagePreviewRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(DaemonServiceServer).GetImagePreview(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: DaemonService_GetImagePreview_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(DaemonServiceServer).GetImagePreview(ctx, req.(*GetImagePreviewRequest))
+ }
+ 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 {
@@ -622,6 +658,10 @@ var DaemonService_ServiceDesc = grpc.ServiceDesc{
MethodName: "ApplyToClipboard",
Handler: _DaemonService_ApplyToClipboard_Handler,
},
+ {
+ MethodName: "GetImagePreview",
+ Handler: _DaemonService_GetImagePreview_Handler,
+ },
{
MethodName: "ListDevices",
Handler: _DaemonService_ListDevices_Handler,
diff --git a/tools/installer/copysync.iss b/tools/installer/copysync.iss
index 3277ceb..7f55c1d 100644
--- a/tools/installer/copysync.iss
+++ b/tools/installer/copysync.iss
@@ -1,97 +1,98 @@
-; CopySync 的 Windows 安装程序(Inno Setup 6)。由 scripts\build-windows.ps1 调用:
-;
-; iscc /DAppVersion=1.2.0 /DSourceDir=<构建好的目录> /DOutputDir=<输出目录> tools\installer\copysync.iss
-;
-; 按用户安装:装到 %LOCALAPPDATA%\Programs\CopySync,不需要管理员权限、不弹 UAC。
-; 数据目录 %LOCALAPPDATA%\CopySync 与安装目录分开,升级、重装都不受影响。
-
-#ifndef AppVersion
- #define AppVersion "0.0.0"
-#endif
-#ifndef SourceDir
- #define SourceDir "..\..\dist\windows\CopySync"
-#endif
-#ifndef OutputDir
- #define OutputDir "..\..\dist\windows"
-#endif
-
-[Setup]
-; AppId 一旦发布就不能再改:Windows 靠它认出这是同一个程序的升级
-AppId={{13E09E3B-04CA-435D-A596-19D818B1BE24}
-AppName=CopySync
-AppVersion={#AppVersion}
-AppVerName=CopySync {#AppVersion}
-AppPublisher=baiyuze
-AppPublisherURL=https://baiyuze.github.io/copysync/
-AppSupportURL=https://github.com/baiyuze/copysync/issues
-DefaultDirName={localappdata}\Programs\CopySync
-DisableDirPage=yes
-DisableProgramGroupPage=yes
-PrivilegesRequired=lowest
-OutputDir={#OutputDir}
-OutputBaseFilename=CopySync-Setup
-Compression=lzma2
-SolidCompression=yes
-WizardStyle=modern
-ArchitecturesAllowed=x64compatible
-ArchitecturesInstallIn64BitMode=x64compatible
-; Windows 10 21H2 起
-MinVersion=10.0.19044
-SetupIconFile=..\..\ui\windows\runner\resources\app_icon.ico
-UninstallDisplayIcon={app}\CopySync.exe
-UninstallDisplayName=CopySync
-; 用「重启管理器」关掉正在运行的界面,免得文件被占用
-CloseApplications=yes
-RestartApplications=no
-ShowLanguageDialog=no
-
-[Languages]
-; 简体中文的翻译文件不是每个 Inno Setup 版本都自带,有就用
-#if FileExists(AddBackslash(CompilerPath) + "Languages\ChineseSimplified.isl")
-Name: "chinesesimplified"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
-#endif
-Name: "english"; MessagesFile: "compiler:Default.isl"
-
-[Files]
-Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: recursesubdirs ignoreversion
-
-[Icons]
-Name: "{autoprograms}\CopySync"; Filename: "{app}\CopySync.exe"
-
-[Registry]
-; 卸载时删掉开机自启项与窗口位置记录。ValueType: none 表示安装时不写,只在卸载时删
-Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueName: "CopySync"; ValueType: none; Flags: uninsdeletevalue
-Root: HKCU; Subkey: "Software\CopySync"; ValueType: none; Flags: uninsdeletekey
-
-[Run]
-; 升级前停掉了后台服务;之前启用过后台同步的话,装完立刻重新拉起,不必等用户打开界面
-Filename: "{app}\copysyncd.exe"; Parameters: "-supervise"; Flags: nowait runhidden; Check: AutostartRegistered
-Filename: "{app}\CopySync.exe"; Description: "{cm:LaunchProgram,CopySync}"; Flags: nowait postinstall skipifsilent
-
-[UninstallRun]
-Filename: "{sys}\taskkill.exe"; Parameters: "/F /T /IM copysyncd.exe"; Flags: runhidden; RunOnceId: "StopDaemon"
-Filename: "{sys}\taskkill.exe"; Parameters: "/F /IM CopySync.exe"; Flags: runhidden; RunOnceId: "StopUI"
-
-[Code]
-function AutostartRegistered: Boolean;
-begin
- Result := RegValueExists(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 'CopySync');
-end;
-
-// 后台服务(含守护进程)没有可见窗口,重启管理器关不掉它,安装前直接结束
-function PrepareToInstall(var NeedsRestart: Boolean): String;
-var
- Code: Integer;
-begin
- Exec(ExpandConstant('{sys}\taskkill.exe'), '/F /T /IM copysyncd.exe', '', SW_HIDE, ewWaitUntilTerminated, Code);
- Result := '';
-end;
-
-procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
-begin
- if (CurUninstallStep = usPostUninstall) and not UninstallSilent then
- if MsgBox('是否同时删除复制记录、缓存与这台电脑的设备身份?' + #13#10 + #13#10 +
- '选「否」则保留,重新安装后配对关系和记录都还在。',
- mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES then
- DelTree(ExpandConstant('{localappdata}\CopySync'), True, True, True);
-end;
+; CopySync 的 Windows 安装程序(Inno Setup 6)。由 scripts\build-windows.ps1 调用:
+;
+; iscc /DAppVersion=1.2.0 /DSourceDir=<构建好的目录> /DOutputDir=<输出目录> tools\installer\copysync.iss
+;
+; 按用户安装:装到 %LOCALAPPDATA%\Programs\CopySync,不需要管理员权限、不弹 UAC。
+; 数据目录 %LOCALAPPDATA%\CopySync 与安装目录分开,升级、重装都不受影响。
+
+#ifndef AppVersion
+ #define AppVersion "0.0.0"
+#endif
+#ifndef SourceDir
+ #define SourceDir "..\..\dist\windows\CopySync"
+#endif
+#ifndef OutputDir
+ #define OutputDir "..\..\dist\windows"
+#endif
+
+[Setup]
+; AppId 一旦发布就不能再改:Windows 靠它认出这是同一个程序的升级
+AppId={{13E09E3B-04CA-435D-A596-19D818B1BE24}
+AppName=CopySync
+AppVersion={#AppVersion}
+AppVerName=CopySync {#AppVersion}
+AppPublisher=baiyuze
+AppPublisherURL=https://baiyuze.github.io/copysync/
+AppSupportURL=https://github.com/baiyuze/copysync/issues
+DefaultDirName={localappdata}\Programs\CopySync
+DisableDirPage=yes
+DisableProgramGroupPage=yes
+PrivilegesRequired=lowest
+OutputDir={#OutputDir}
+OutputBaseFilename=CopySync-Setup
+Compression=lzma2
+SolidCompression=yes
+WizardStyle=modern
+ArchitecturesAllowed=x64compatible
+ArchitecturesInstallIn64BitMode=x64compatible
+; Windows 10 21H2 起
+MinVersion=10.0.19044
+SetupIconFile=..\..\ui\windows\runner\resources\app_icon.ico
+UninstallDisplayIcon={app}\CopySync.exe
+UninstallDisplayName=CopySync
+; 用「重启管理器」关掉正在运行的界面,免得文件被占用
+CloseApplications=yes
+RestartApplications=no
+ShowLanguageDialog=no
+
+[Languages]
+; 简体中文的翻译文件不是每个 Inno Setup 版本都自带,有就用
+#if FileExists(AddBackslash(CompilerPath) + "Languages\ChineseSimplified.isl")
+Name: "chinesesimplified"; MessagesFile: "compiler:Languages\ChineseSimplified.isl"
+#endif
+Name: "english"; MessagesFile: "compiler:Default.isl"
+
+[Files]
+Source: "{#SourceDir}\*"; DestDir: "{app}"; Flags: recursesubdirs ignoreversion
+
+[Icons]
+Name: "{autoprograms}\CopySync"; Filename: "{app}\CopySync.exe"
+Name: "{autodesktop}\CopySync"; Filename: "{app}\CopySync.exe"
+
+[Registry]
+; 卸载时删掉开机自启项与窗口位置记录。ValueType: none 表示安装时不写,只在卸载时删
+Root: HKCU; Subkey: "Software\Microsoft\Windows\CurrentVersion\Run"; ValueName: "CopySync"; ValueType: none; Flags: uninsdeletevalue
+Root: HKCU; Subkey: "Software\CopySync"; ValueType: none; Flags: uninsdeletekey
+
+[Run]
+; 升级前停掉了后台服务;之前启用过后台同步的话,装完立刻重新拉起,不必等用户打开界面
+Filename: "{app}\copysyncd.exe"; Parameters: "-supervise"; Flags: nowait runhidden; Check: AutostartRegistered
+Filename: "{app}\CopySync.exe"; Description: "{cm:LaunchProgram,CopySync}"; Flags: nowait postinstall skipifsilent
+
+[UninstallRun]
+Filename: "{sys}\taskkill.exe"; Parameters: "/F /T /IM copysyncd.exe"; Flags: runhidden; RunOnceId: "StopDaemon"
+Filename: "{sys}\taskkill.exe"; Parameters: "/F /IM CopySync.exe"; Flags: runhidden; RunOnceId: "StopUI"
+
+[Code]
+function AutostartRegistered: Boolean;
+begin
+ Result := RegValueExists(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 'CopySync');
+end;
+
+// 后台服务(含守护进程)没有可见窗口,重启管理器关不掉它,安装前直接结束
+function PrepareToInstall(var NeedsRestart: Boolean): String;
+var
+ Code: Integer;
+begin
+ Exec(ExpandConstant('{sys}\taskkill.exe'), '/F /T /IM copysyncd.exe', '', SW_HIDE, ewWaitUntilTerminated, Code);
+ Result := '';
+end;
+
+procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
+begin
+ if (CurUninstallStep = usPostUninstall) and not UninstallSilent then
+ if MsgBox('是否同时删除复制记录、缓存与这台电脑的设备身份?' + #13#10 + #13#10 +
+ '选「否」则保留,重新安装后配对关系和记录都还在。',
+ mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES then
+ DelTree(ExpandConstant('{localappdata}\CopySync'), True, True, True);
+end;
diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dart
index a3f7274..1aef20a 100644
--- a/ui/lib/app_state.dart
+++ b/ui/lib/app_state.dart
@@ -37,6 +37,7 @@ class AppState extends ChangeNotifier {
/// 待用户核对指纹的配对请求。非空时界面弹出确认。
Device? _pendingPairing;
+ final Set<String> _handledPairingSessions = {};
/// 连不上后台服务时,它的安装状态。界面据此决定显示欢迎页还是重启提示。
ServiceState? _serviceState;
@@ -284,7 +285,7 @@ class AppState extends ChangeNotifier {
void _onDeviceChanged(Device d) {
// 带 pairingSession 的不是已配对设备,而是一条待确认的配对请求
if (d.pairingSession.isNotEmpty) {
- _pendingPairing = d;
+ _setPendingPairing(d);
return;
}
final i = _peers.indexWhere((p) => p.id == d.id);
@@ -315,21 +316,32 @@ class AppState extends ChangeNotifier {
final resp = await _client.redeemPairingCode(
RedeemPairingCodeRequest(code: code.trim().toUpperCase()),
);
- _pendingPairing = resp.peer..pairingSession = resp.pairingSession;
+ final peer = resp.peer..pairingSession = resp.pairingSession;
+ _setPendingPairing(peer);
notifyListeners();
- return _pendingPairing!;
+ return peer;
}
Future<void> confirmPairing(String session, bool accept) async {
await _client.confirmPairing(
ConfirmPairingRequest(pairingSession: session, accept: accept),
);
- _pendingPairing = null;
+ dismissPendingPairing(session);
await _loadDevices();
}
- void dismissPendingPairing() {
- _pendingPairing = null;
+ void _setPendingPairing(Device peer) {
+ // 事件流和兑换 RPC 返回同一个会话,先后顺序不固定。
+ if (!_handledPairingSessions.contains(peer.pairingSession)) {
+ _pendingPairing = peer;
+ }
+ }
+
+ void dismissPendingPairing([String? session]) {
+ final handled = session ?? _pendingPairing?.pairingSession;
+ if (handled != null) _handledPairingSessions.add(handled);
+ // 确认旧会话期间可能来了另一条请求,不能把新请求一并清掉。
+ if (_pendingPairing?.pairingSession == handled) _pendingPairing = null;
notifyListeners();
}
@@ -359,9 +371,18 @@ class AppState extends ChangeNotifier {
Future<void> fetch(String clipId) =>
_client.fetch(FetchRequest(clipId: clipId));
+ Future<void> fetchImagePreview(String clipId) =>
+ _client.fetch(FetchRequest(clipId: clipId, preserveClipboard: true));
+
Future<void> applyToClipboard(String clipId) =>
_client.applyToClipboard(ApplyToClipboardRequest(clipId: clipId));
+ Future<String> imagePreviewPath(String clipId) async {
+ final response = await _client.getImagePreview(GetImagePreviewRequest(clipId: clipId),
+ options: CallOptions(timeout: const Duration(seconds: 10)));
+ return response.path;
+ }
+
Future<void> requestClipboardPermission() =>
_client.requestClipboardPermission(Empty());
diff --git a/ui/lib/gen/copysync/v1/daemon.pb.dart b/ui/lib/gen/copysync/v1/daemon.pb.dart
index e1328ae..3e18176 100644
--- a/ui/lib/gen/copysync/v1/daemon.pb.dart
+++ b/ui/lib/gen/copysync/v1/daemon.pb.dart
@@ -1014,9 +1014,11 @@ class DeleteHistoryRequest extends $pb.GeneratedMessage {
class FetchRequest extends $pb.GeneratedMessage {
factory FetchRequest({
$core.String? clipId,
+ $core.bool? preserveClipboard,
}) {
final result = FetchRequest._();
if (clipId != null) result.clipId = clipId;
+ if (preserveClipboard != null) result.preserveClipboard = preserveClipboard;
return result;
}
@@ -1034,6 +1036,7 @@ class FetchRequest extends $pb.GeneratedMessage {
package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),
createEmptyInstance: FetchRequest.$_createMessage)
..aOS(1, _omitFieldNames ? '' : 'clipId')
+ ..aOB(2, _omitFieldNames ? '' : 'preserveClipboard')
..hasRequiredFields = false;
@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
@@ -1066,6 +1069,15 @@ class FetchRequest extends $pb.GeneratedMessage {
$core.bool hasClipId() => $_has(0);
@$pb.TagNumber(1)
void clearClipId() => $_clearField(1);
+
+ @$pb.TagNumber(2)
+ $core.bool get preserveClipboard => $_getBF(1);
+ @$pb.TagNumber(2)
+ set preserveClipboard($core.bool value) => $_setBool(1, value);
+ @$pb.TagNumber(2)
+ $core.bool hasPreserveClipboard() => $_has(1);
+ @$pb.TagNumber(2)
+ void clearPreserveClipboard() => $_clearField(2);
}
class ApplyToClipboardRequest extends $pb.GeneratedMessage {
@@ -2044,6 +2056,124 @@ class Status extends $pb.GeneratedMessage {
void clearVersion() => $_clearField(7);
}
+class GetImagePreviewRequest extends $pb.GeneratedMessage {
+ factory GetImagePreviewRequest({
+ $core.String? clipId,
+ }) {
+ final result = GetImagePreviewRequest._();
+ if (clipId != null) result.clipId = clipId;
+ return result;
+ }
+
+ GetImagePreviewRequest._();
+
+ factory GetImagePreviewRequest.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ GetImagePreviewRequest()..mergeFromBuffer(data, registry);
+ factory GetImagePreviewRequest.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ GetImagePreviewRequest()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'GetImagePreviewRequest',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),
+ createEmptyInstance: GetImagePreviewRequest.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'clipId')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ GetImagePreviewRequest clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ GetImagePreviewRequest copyWith(
+ void Function(GetImagePreviewRequest) updates) =>
+ super.copyWith((message) => updates(message as GetImagePreviewRequest))
+ as GetImagePreviewRequest;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated(
+ 'Use GetImagePreviewRequest() / GetImagePreviewRequest.new instead')
+ static GetImagePreviewRequest create() => GetImagePreviewRequest._();
+ static $pb.GeneratedMessage $_createMessage() => GetImagePreviewRequest._();
+ @$core.override
+ GetImagePreviewRequest createEmptyInstance() => GetImagePreviewRequest._();
+ @$core.pragma('dart2js:noInline')
+ static GetImagePreviewRequest getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<GetImagePreviewRequest>(
+ GetImagePreviewRequest.$_createMessage);
+ static GetImagePreviewRequest? _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 GetImagePreviewResponse extends $pb.GeneratedMessage {
+ factory GetImagePreviewResponse({
+ $core.String? path,
+ }) {
+ final result = GetImagePreviewResponse._();
+ if (path != null) result.path = path;
+ return result;
+ }
+
+ GetImagePreviewResponse._();
+
+ factory GetImagePreviewResponse.fromBuffer($core.List<$core.int> data,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ GetImagePreviewResponse()..mergeFromBuffer(data, registry);
+ factory GetImagePreviewResponse.fromJson($core.String json,
+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>
+ GetImagePreviewResponse()..mergeFromJson(json, registry);
+
+ static final $pb.BuilderInfo _i = $pb.BuilderInfo(
+ _omitMessageNames ? '' : 'GetImagePreviewResponse',
+ package: const $pb.PackageName(_omitMessageNames ? '' : 'copysync.v1'),
+ createEmptyInstance: GetImagePreviewResponse.$_createMessage)
+ ..aOS(1, _omitFieldNames ? '' : 'path')
+ ..hasRequiredFields = false;
+
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ GetImagePreviewResponse clone() => deepCopy();
+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')
+ GetImagePreviewResponse copyWith(
+ void Function(GetImagePreviewResponse) updates) =>
+ super.copyWith((message) => updates(message as GetImagePreviewResponse))
+ as GetImagePreviewResponse;
+
+ @$core.override
+ $pb.BuilderInfo get info_ => _i;
+
+ @$core.pragma('dart2js:noInline')
+ @$core.Deprecated(
+ 'Use GetImagePreviewResponse() / GetImagePreviewResponse.new instead')
+ static GetImagePreviewResponse create() => GetImagePreviewResponse._();
+ static $pb.GeneratedMessage $_createMessage() => GetImagePreviewResponse._();
+ @$core.override
+ GetImagePreviewResponse createEmptyInstance() => GetImagePreviewResponse._();
+ @$core.pragma('dart2js:noInline')
+ static GetImagePreviewResponse getDefault() => _defaultInstance ??=
+ $pb.GeneratedMessage.$_defaultFor<GetImagePreviewResponse>(
+ GetImagePreviewResponse.$_createMessage);
+ static GetImagePreviewResponse? _defaultInstance;
+
+ @$pb.TagNumber(1)
+ $core.String get path => $_getSZ(0);
+ @$pb.TagNumber(1)
+ set path($core.String value) => $_setString(0, value);
+ @$pb.TagNumber(1)
+ $core.bool hasPath() => $_has(0);
+ @$pb.TagNumber(1)
+ void clearPath() => $_clearField(1);
+}
+
const $core.bool _omitFieldNames =
$core.bool.fromEnvironment('protobuf.omit_field_names');
const $core.bool _omitMessageNames =
diff --git a/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart
index b9ae589..b43bd58 100644
--- a/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart
+++ b/ui/lib/gen/copysync/v1/daemon.pbgrpc.dart
@@ -72,6 +72,14 @@ class DaemonServiceClient extends $grpc.Client {
return $createUnaryCall(_$applyToClipboard, request, options: options);
}
+ /// 只返回已就绪图片在本机的路径,不改动剪贴板,也不把路径发给对端。
+ $grpc.ResponseFuture<$0.GetImagePreviewResponse> getImagePreview(
+ $0.GetImagePreviewRequest request, {
+ $grpc.CallOptions? options,
+ }) {
+ return $createUnaryCall(_$getImagePreview, request, options: options);
+ }
+
$grpc.ResponseFuture<$0.ListDevicesResponse> listDevices(
$0.Empty request, {
$grpc.CallOptions? options,
@@ -171,6 +179,11 @@ class DaemonServiceClient extends $grpc.Client {
'/copysync.v1.DaemonService/ApplyToClipboard',
($0.ApplyToClipboardRequest value) => value.writeToBuffer(),
$0.Empty.fromBuffer);
+ static final _$getImagePreview =
+ $grpc.ClientMethod<$0.GetImagePreviewRequest, $0.GetImagePreviewResponse>(
+ '/copysync.v1.DaemonService/GetImagePreview',
+ ($0.GetImagePreviewRequest value) => value.writeToBuffer(),
+ $0.GetImagePreviewResponse.fromBuffer);
static final _$listDevices =
$grpc.ClientMethod<$0.Empty, $0.ListDevicesResponse>(
'/copysync.v1.DaemonService/ListDevices',
@@ -262,6 +275,15 @@ abstract class DaemonServiceBase extends $grpc.Service {
($core.List<$core.int> value) =>
$0.ApplyToClipboardRequest.fromBuffer(value),
($0.Empty value) => value.writeToBuffer()));
+ $addMethod($grpc.ServiceMethod<$0.GetImagePreviewRequest,
+ $0.GetImagePreviewResponse>(
+ 'GetImagePreview',
+ getImagePreview_Pre,
+ false,
+ false,
+ ($core.List<$core.int> value) =>
+ $0.GetImagePreviewRequest.fromBuffer(value),
+ ($0.GetImagePreviewResponse value) => value.writeToBuffer()));
$addMethod($grpc.ServiceMethod<$0.Empty, $0.ListDevicesResponse>(
'ListDevices',
listDevices_Pre,
@@ -377,6 +399,15 @@ abstract class DaemonServiceBase extends $grpc.Service {
$async.Future<$0.Empty> applyToClipboard(
$grpc.ServiceCall call, $0.ApplyToClipboardRequest request);
+ $async.Future<$0.GetImagePreviewResponse> getImagePreview_Pre(
+ $grpc.ServiceCall $call,
+ $async.Future<$0.GetImagePreviewRequest> $request) async {
+ return getImagePreview($call, await $request);
+ }
+
+ $async.Future<$0.GetImagePreviewResponse> getImagePreview(
+ $grpc.ServiceCall call, $0.GetImagePreviewRequest request);
+
$async.Future<$0.ListDevicesResponse> listDevices_Pre(
$grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {
return listDevices($call, await $request);
diff --git a/ui/lib/gen/copysync/v1/daemon.pbjson.dart b/ui/lib/gen/copysync/v1/daemon.pbjson.dart
index db6061c..708f1c6 100644
--- a/ui/lib/gen/copysync/v1/daemon.pbjson.dart
+++ b/ui/lib/gen/copysync/v1/daemon.pbjson.dart
@@ -378,12 +378,20 @@ const FetchRequest$json = {
'1': 'FetchRequest',
'2': [
{'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},
+ {
+ '1': 'preserve_clipboard',
+ '3': 2,
+ '4': 1,
+ '5': 8,
+ '10': 'preserveClipboard'
+ },
],
};
/// Descriptor for `FetchRequest`. Decode as a `google.protobuf.DescriptorProto`.
-final $typed_data.Uint8List fetchRequestDescriptor = $convert
- .base64Decode('CgxGZXRjaFJlcXVlc3QSFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElk');
+final $typed_data.Uint8List fetchRequestDescriptor = $convert.base64Decode(
+ 'CgxGZXRjaFJlcXVlc3QSFwoHY2xpcF9pZBgBIAEoCVIGY2xpcElkEi0KEnByZXNlcnZlX2NsaX'
+ 'Bib2FyZBgCIAEoCFIRcHJlc2VydmVDbGlwYm9hcmQ=');
@$core.Deprecated('Use applyToClipboardRequestDescriptor instead')
const ApplyToClipboardRequest$json = {
@@ -628,3 +636,29 @@ final $typed_data.Uint8List statusDescriptor = $convert.base64Decode(
'lwYm9hcmRQZXJtaXNzaW9uUhNjbGlwYm9hcmRQZXJtaXNzaW9uEigKEGNhY2hlX2J5dGVzX3Vz'
'ZWQYBSABKANSDmNhY2hlQnl0ZXNVc2VkEiEKDHBlZXJzX29ubGluZRgGIAEoBVILcGVlcnNPbm'
'xpbmUSGAoHdmVyc2lvbhgHIAEoCVIHdmVyc2lvbg==');
+
+@$core.Deprecated('Use getImagePreviewRequestDescriptor instead')
+const GetImagePreviewRequest$json = {
+ '1': 'GetImagePreviewRequest',
+ '2': [
+ {'1': 'clip_id', '3': 1, '4': 1, '5': 9, '10': 'clipId'},
+ ],
+};
+
+/// Descriptor for `GetImagePreviewRequest`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List getImagePreviewRequestDescriptor =
+ $convert.base64Decode(
+ 'ChZHZXRJbWFnZVByZXZpZXdSZXF1ZXN0EhcKB2NsaXBfaWQYASABKAlSBmNsaXBJZA==');
+
+@$core.Deprecated('Use getImagePreviewResponseDescriptor instead')
+const GetImagePreviewResponse$json = {
+ '1': 'GetImagePreviewResponse',
+ '2': [
+ {'1': 'path', '3': 1, '4': 1, '5': 9, '10': 'path'},
+ ],
+};
+
+/// Descriptor for `GetImagePreviewResponse`. Decode as a `google.protobuf.DescriptorProto`.
+final $typed_data.Uint8List getImagePreviewResponseDescriptor =
+ $convert.base64Decode(
+ 'ChdHZXRJbWFnZVByZXZpZXdSZXNwb25zZRISCgRwYXRoGAEgASgJUgRwYXRo');
diff --git a/ui/lib/main.dart b/ui/lib/main.dart
index e600764..c936fc9 100644
--- a/ui/lib/main.dart
+++ b/ui/lib/main.dart
@@ -98,6 +98,11 @@ class _ShellState extends State<Shell> {
if (pending != null && !_pairingDialogOpen) {
_pairingDialogOpen = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
+ if (!mounted) return;
+ if (state.pendingPairing?.pairingSession != pending.pairingSession) {
+ setState(() => _pairingDialogOpen = false);
+ return;
+ }
await showPairingConfirmDialog(context, pending);
if (mounted) setState(() => _pairingDialogOpen = false);
});
diff --git a/ui/lib/pages/devices_page.dart b/ui/lib/pages/devices_page.dart
index b070166..271fdee 100644
--- a/ui/lib/pages/devices_page.dart
+++ b/ui/lib/pages/devices_page.dart
@@ -78,8 +78,7 @@ class DevicesPage extends StatelessWidget {
);
}
- void _startPairing(BuildContext context) =>
- showDialog(context: context, builder: (_) => const PairingDialog());
+ void _startPairing(BuildContext context) => showPairingDialog(context);
}
class _DeviceRow extends StatelessWidget {
diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dart
index 4daa76c..2669ce5 100644
--- a/ui/lib/pages/history_page.dart
+++ b/ui/lib/pages/history_page.dart
@@ -5,6 +5,7 @@ import '../gen/copysync/v1/daemon.pb.dart';
import '../main.dart';
import '../theme.dart';
import '../widgets/common.dart';
+import '../widgets/image_preview_dialog.dart';
import '../icons.dart';
import '../platform.dart';
@@ -187,47 +188,52 @@ class _RecordRowState extends State<_RecordRow> {
final p = context.palette;
return MouseRegion(
+ cursor: r.kind == ClipKind.CLIP_KIND_IMAGE ? SystemMouseCursors.click : MouseCursor.defer,
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,
- ),
- ],
+ child: InkWell(
+ onTap: r.kind == ClipKind.CLIP_KIND_IMAGE ? () => _preview(r) : null,
+ borderRadius: BorderRadius.circular(Radii.sm),
+ 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),
- ],
+ const SizedBox(width: Insets.md),
+ _trailing(context, r),
+ ],
+ ),
),
),
);
@@ -267,25 +273,31 @@ class _RecordRowState extends State<_RecordRow> {
return Text('已过期', style: context.text.bodySmall?.copyWith(color: p.textFaint));
default:
// 悬停时才显示操作,静态时列表保持干净
- if (!_hovered) return const SizedBox(height: 28);
+ if (!_hovered && r.kind != ClipKind.CLIP_KIND_IMAGE) 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: AppIcons.trash,
- tooltip: '删除这条记录',
- onTap: () => _run(() => AppScope.read(context).deleteRecords(ids: [r.id]), '已删除'),
- ),
+ if (r.kind == ClipKind.CLIP_KIND_IMAGE)
+ TextButton(onPressed: () => _preview(r), child: const Text('预览')),
+ if (_hovered) ...[
+ TextButton(
+ onPressed: () =>
+ _run(() => AppScope.read(context).applyToClipboard(r.id), '已放入剪贴板'),
+ child: const Text('放入剪贴板'),
+ ),
+ IconAction(
+ icon: AppIcons.trash,
+ tooltip: '删除这条记录',
+ onTap: () => _run(() => AppScope.read(context).deleteRecords(ids: [r.id]), '已删除'),
+ ),
+ ],
],
);
}
}
+ void _preview(ClipRecord record) => showImagePreview(context, record.id);
+
Future<void> _run(Future<void> Function() action, String success) async {
setState(() => _busy = true);
try {
diff --git a/ui/lib/widgets/image_preview_dialog.dart b/ui/lib/widgets/image_preview_dialog.dart
new file mode 100644
index 0000000..bb28fc4
--- /dev/null
+++ b/ui/lib/widgets/image_preview_dialog.dart
@@ -0,0 +1,214 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+
+import '../app_state.dart';
+import '../gen/copysync/v1/daemon.pb.dart';
+import '../icons.dart';
+import '../main.dart';
+import '../theme.dart';
+
+Future<void> showImagePreview(BuildContext context, String clipId) =>
+ showDialog<void>(
+ context: context,
+ builder: (_) => ImagePreviewDialog(clipId: clipId),
+ );
+
+class ImagePreviewDialog extends StatefulWidget {
+ const ImagePreviewDialog({super.key, required this.clipId});
+
+ final String clipId;
+
+ @override
+ State<ImagePreviewDialog> createState() => _ImagePreviewDialogState();
+}
+
+class _ImagePreviewDialogState extends State<ImagePreviewDialog> {
+ final _transform = TransformationController();
+ Future<String>? _preview;
+ bool _requesting = false;
+ String? _downloadError;
+
+ @override
+ void dispose() {
+ _transform.dispose();
+ super.dispose();
+ }
+
+ Future<void> _download() async {
+ if (_requesting) return;
+ setState(() {
+ _requesting = true;
+ _downloadError = null;
+ _preview = null;
+ });
+ try {
+ await AppScope.read(context).fetchImagePreview(widget.clipId);
+ } catch (e) {
+ if (mounted) setState(() => _downloadError = AppState.describeError(e));
+ } finally {
+ if (mounted) setState(() => _requesting = false);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final state = AppScope.of(context);
+ final record = state.records
+ .where((r) => r.id == widget.clipId)
+ .firstOrNull;
+ return Dialog(
+ insetPadding: const EdgeInsets.all(Insets.xl),
+ child: SizedBox(
+ width: 920,
+ height: 640,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ Insets.xl,
+ Insets.md,
+ Insets.md,
+ Insets.md,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text('图片预览', style: context.text.titleMedium),
+ ),
+ IconButton(
+ tooltip: '关闭预览',
+ onPressed: () => Navigator.pop(context),
+ icon: Icon(AppIcons.xmark),
+ ),
+ ],
+ ),
+ ),
+ Expanded(
+ child: Container(
+ width: double.infinity,
+ color: context.palette.fill,
+ child: _content(state, record),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: Insets.xl,
+ vertical: Insets.sm,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text('滚轮或触控板缩放,拖动查看', style: context.text.bodySmall),
+ ),
+ TextButton(
+ onPressed: () => _transform.value = Matrix4.identity(),
+ child: const Text('适应窗口'),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _content(AppState state, ClipRecord? record) {
+ if (record == null) return _message('这条图片记录已被删除');
+ if (record.status == ClipStatus.CLIP_STATUS_EXPIRED) {
+ return _message('图片已过期,无法预览');
+ }
+ if (_requesting || record.status == ClipStatus.CLIP_STATUS_FETCHING) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ CircularProgressIndicator(
+ value: state.progressOf(record.id),
+ strokeWidth: 2,
+ ),
+ const SizedBox(height: Insets.lg),
+ const Text('正在下载图片…'),
+ ],
+ ),
+ );
+ }
+ if (record.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY ||
+ record.status == ClipStatus.CLIP_STATUS_FAILED) {
+ return _message(
+ _downloadError ??
+ (record.status == ClipStatus.CLIP_STATUS_FAILED
+ ? '图片下载失败,请重试'
+ : '图片尚未下载到这台电脑'),
+ action: FilledButton(onPressed: _download, child: const Text('下载并预览')),
+ );
+ }
+ if (record.status != ClipStatus.CLIP_STATUS_READY) {
+ return _message('图片暂时无法预览');
+ }
+
+ _preview ??= state.imagePreviewPath(record.id);
+ return FutureBuilder<String>(
+ future: _preview,
+ builder: (context, snapshot) {
+ if (snapshot.hasError) {
+ return _message(
+ AppState.describeError(snapshot.error!),
+ action: OutlinedButton(
+ onPressed: () => setState(() => _preview = null),
+ child: const Text('重试'),
+ ),
+ );
+ }
+ if (!snapshot.hasData) {
+ return const Center(child: CircularProgressIndicator(strokeWidth: 2));
+ }
+ return InteractiveViewer(
+ transformationController: _transform,
+ minScale: 0.5,
+ maxScale: 8,
+ trackpadScrollCausesScale: true,
+ child: SizedBox.expand(
+ child: Image(
+ key: const ValueKey('image-preview-content'),
+ // 预览限制解码尺寸并保持比例,超大截图不占用整张原图的内存。
+ image: ResizeImage(
+ FileImage(File(snapshot.data!)),
+ width: 2048,
+ height: 2048,
+ policy: ResizeImagePolicy.fit,
+ ),
+ fit: BoxFit.contain,
+ semanticLabel: '复制记录中的图片',
+ frameBuilder: (_, child, frame, synchronous) =>
+ frame != null || synchronous
+ ? child
+ : const Center(
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ errorBuilder: (_, _, _) => _message('无法读取图片,文件可能已被清理或损坏'),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _message(String text, {Widget? action}) => Center(
+ child: Padding(
+ padding: const EdgeInsets.all(Insets.xl),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ text,
+ textAlign: TextAlign.center,
+ style: context.text.bodyMedium,
+ ),
+ if (action != null) ...[const SizedBox(height: Insets.lg), action],
+ ],
+ ),
+ ),
+ );
+}
diff --git a/ui/lib/widgets/pairing_dialog.dart b/ui/lib/widgets/pairing_dialog.dart
index 7ebffa1..49ac06b 100644
--- a/ui/lib/widgets/pairing_dialog.dart
+++ b/ui/lib/widgets/pairing_dialog.dart
@@ -9,6 +9,24 @@ import 'common.dart';
import '../icons.dart';
import '../platform.dart';
+// 保存“添加设备”这条路由。配对请求到达时只移除它,不误关上层的确认框。
+final _pairingSetupRoutes = Expando<DialogRoute<void>>();
+
+Future<void> showPairingDialog(BuildContext context) {
+ final navigator = Navigator.of(context, rootNavigator: true);
+ if (_pairingSetupRoutes[navigator] != null) return Future.value();
+ final route = DialogRoute<void>(
+ context: context,
+ builder: (_) => const PairingDialog(),
+ );
+ _pairingSetupRoutes[navigator] = route;
+ return navigator.push(route).whenComplete(() {
+ if (identical(_pairingSetupRoutes[navigator], route)) {
+ _pairingSetupRoutes[navigator] = null;
+ }
+ });
+}
+
/// 配对对话框:既能生成配对码,也能输入对方的配对码。
///
/// 两种角色放在一个对话框里切换,因为用户在打开它之前
@@ -192,6 +210,7 @@ class _JoinTabState extends State<_JoinTab> {
}
Future<void> _submit() async {
+ if (_busy) return;
final code = _controller.text.trim();
if (code.length != 6) {
setState(() => _error = '配对码是 6 位字母或数字');
@@ -202,10 +221,9 @@ class _JoinTabState extends State<_JoinTab> {
_error = null;
});
try {
- final peer = await AppScope.read(context).redeemPairingCode(code);
- if (!mounted) return;
- Navigator.pop(context);
- await showPairingConfirmDialog(context, peer);
+ // Shell 统一响应 pendingPairing,生成方和输入方都只有一个确认入口。
+ // 事件可能先于 RPC 返回,因此这里也不能 pop 最上层路由。
+ await AppScope.read(context).redeemPairingCode(code);
} catch (e) {
if (mounted) setState(() => _error = AppState.describeError(e));
} finally {
@@ -281,6 +299,12 @@ class _JoinTabState extends State<_JoinTab> {
/// 但无法让两台设备显示出相同的指纹。所以这一步不能做成"点确定就过",
/// 必须让用户真的看见并比对。
Future<void> showPairingConfirmDialog(BuildContext context, Device peer) {
+ final navigator = Navigator.of(context, rootNavigator: true);
+ final setup = _pairingSetupRoutes[navigator];
+ if (setup != null) {
+ _pairingSetupRoutes[navigator] = null;
+ if (setup.isActive) navigator.removeRoute(setup);
+ }
return showDialog<void>(
context: context,
barrierDismissible: false,
@@ -301,6 +325,7 @@ class _PairingConfirmDialogState extends State<PairingConfirmDialog> {
bool _busy = false;
Future<void> _respond(bool accept) async {
+ if (_busy) return;
setState(() => _busy = true);
final state = AppScope.read(context);
try {
@@ -309,6 +334,7 @@ class _PairingConfirmDialogState extends State<PairingConfirmDialog> {
Navigator.pop(context);
showToast(context, accept ? '配对完成' : '已拒绝配对');
} catch (e) {
+ state.dismissPendingPairing(widget.peer.pairingSession);
if (!mounted) return;
Navigator.pop(context);
showToast(context, AppState.describeError(e), error: true);
diff --git a/ui/test/fixtures/image-preview.png b/ui/test/fixtures/image-preview.png
new file mode 100644
index 0000000..72dea20
Binary files /dev/null and b/ui/test/fixtures/image-preview.png differ
diff --git a/ui/test/image_preview_test.dart b/ui/test/image_preview_test.dart
new file mode 100644
index 0000000..d551380
--- /dev/null
+++ b/ui/test/image_preview_test.dart
@@ -0,0 +1,210 @@
+import 'dart:io';
+
+import 'package:copysync_ui/app_state.dart';
+import 'package:copysync_ui/gen/copysync/v1/daemon.pb.dart';
+import 'package:copysync_ui/main.dart';
+import 'package:copysync_ui/widgets/image_preview_dialog.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+class PreviewState extends AppState {
+ PreviewState(this.path, {ClipStatus status = ClipStatus.CLIP_STATUS_READY}) {
+ debugSeed(
+ status: Status(signalingConnected: true),
+ config: Config(),
+ self: Device(id: 'self'),
+ records: [
+ ClipRecord(
+ id: 'image',
+ kind: ClipKind.CLIP_KIND_IMAGE,
+ status: status,
+ textPreview: '测试图片',
+ originDeviceName: '测试电脑',
+ ),
+ ],
+ );
+ }
+ String path;
+ int previewCalls = 0;
+ int fetchCalls = 0;
+ int clipboardCalls = 0;
+ bool failPreview = false;
+ bool failFetch = false;
+
+ @override
+ Future<String> imagePreviewPath(String clipId) async {
+ previewCalls++;
+ if (failPreview) throw StateError('图片已不在本机,可能已被清理');
+ return path;
+ }
+
+ @override
+ Future<void> applyToClipboard(String clipId) async {
+ clipboardCalls++;
+ }
+
+ @override
+ Future<void> fetchImagePreview(String clipId) async {
+ fetchCalls++;
+ if (failFetch) throw StateError('对方设备暂时离线');
+ setStatus(ClipStatus.CLIP_STATUS_FETCHING);
+ }
+
+ void setStatus(ClipStatus status) => debugEvent(
+ Event(clipUpdated: records.single.deepCopy()..status = status),
+ );
+}
+
+Future<void> openPreview(
+ WidgetTester tester,
+ PreviewState state, {
+ bool button = false,
+}) async {
+ await tester.pumpWidget(CopySyncApp(state: state));
+ await tester.pump();
+ await tester.tap(find.text(button ? '预览' : '测试图片'));
+ await tester.pump(const Duration(milliseconds: 250));
+ expect(find.byType(ImagePreviewDialog), findsOneWidget);
+}
+
+Future<RawImage> decodedImage(WidgetTester tester) async {
+ final finder = find.descendant(
+ of: find.byKey(const ValueKey('image-preview-content')),
+ matching: find.byType(RawImage),
+ );
+ for (var i = 0; i < 60; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 50)),
+ );
+ await tester.pump();
+ if (finder.evaluate().isNotEmpty) {
+ final image = tester.widget<RawImage>(finder);
+ if (image.image != null) return image;
+ }
+ }
+ throw StateError('图片未成功解码');
+}
+
+void main() {
+ testWidgets('点击图片记录可预览、缩放和关闭,不修改剪贴板', (tester) async {
+ final state = PreviewState(
+ File('test/fixtures/image-preview.png').absolute.path,
+ );
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ final image = await decodedImage(tester);
+ expect(image.image!.width, 16);
+ expect(image.image!.height, 16);
+ expect(state.previewCalls, 1);
+ expect(state.clipboardCalls, 0);
+ final viewer = tester.widget<InteractiveViewer>(
+ find.byType(InteractiveViewer),
+ );
+ viewer.transformationController!.value = Matrix4.diagonal3Values(2, 2, 1);
+ await tester.tap(find.text('适应窗口'));
+ await tester.pump();
+ expect(viewer.transformationController!.value, Matrix4.identity());
+ await tester.tap(find.byTooltip('关闭预览'));
+ await tester.pumpAndSettle();
+ expect(find.byType(ImagePreviewDialog), findsNothing);
+ expect(state.clipboardCalls, 0);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('预览按钮同样打开图片', (tester) async {
+ final state = PreviewState(
+ File('test/fixtures/image-preview.png').absolute.path,
+ );
+ addTearDown(state.dispose);
+ await openPreview(tester, state, button: true);
+ await decodedImage(tester);
+ expect(state.clipboardCalls, 0);
+ });
+
+ testWidgets('远端图片明确下载,进度结束后自动显示预览', (tester) async {
+ final state = PreviewState(
+ File('test/fixtures/image-preview.png').absolute.path,
+ status: ClipStatus.CLIP_STATUS_REMOTE_ONLY,
+ );
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ expect(find.text('图片尚未下载到这台电脑'), findsOneWidget);
+ expect(state.previewCalls, 0);
+ await tester.tap(find.text('下载并预览'));
+ await tester.pump();
+ expect(find.text('正在下载图片…'), findsOneWidget);
+ expect(state.fetchCalls, 1);
+ state.setStatus(ClipStatus.CLIP_STATUS_READY);
+ await tester.pump();
+ await decodedImage(tester);
+ expect(state.previewCalls, 1);
+ expect(state.clipboardCalls, 0);
+ });
+
+ testWidgets('下载失败显示原因并允许重试', (tester) async {
+ final state = PreviewState('', status: ClipStatus.CLIP_STATUS_REMOTE_ONLY)
+ ..failFetch = true;
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ await tester.tap(find.text('下载并预览'));
+ await tester.pumpAndSettle();
+ expect(find.text('对方设备暂时离线'), findsOneWidget);
+ expect(find.text('下载并预览'), findsOneWidget);
+ expect(state.previewCalls, 0);
+ });
+
+ testWidgets('图片过期或记录被删除时不再读取本地文件', (tester) async {
+ final state = PreviewState('', status: ClipStatus.CLIP_STATUS_EXPIRED);
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ expect(find.text('图片已过期,无法预览'), findsOneWidget);
+ state.debugEvent(Event(clipRemoved: 'image'));
+ await tester.pumpAndSettle();
+ expect(find.text('这条图片记录已被删除'), findsOneWidget);
+ expect(state.previewCalls, 0);
+ });
+
+ testWidgets('读取接口失败可重试,预览期间记录过期立即隐藏图片', (tester) async {
+ final state = PreviewState(
+ File('test/fixtures/image-preview.png').absolute.path,
+ )..failPreview = true;
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ await tester.pumpAndSettle();
+ expect(find.text('图片已不在本机,可能已被清理'), findsOneWidget);
+ state.failPreview = false;
+ await tester.tap(find.text('重试'));
+ await tester.pump();
+ await decodedImage(tester);
+ expect(state.previewCalls, 2);
+ state.setStatus(ClipStatus.CLIP_STATUS_EXPIRED);
+ await tester.pumpAndSettle();
+ expect(find.text('图片已过期,无法预览'), findsOneWidget);
+ expect(find.byKey(const ValueKey('image-preview-content')), findsNothing);
+ expect(state.clipboardCalls, 0);
+ });
+
+ for (final corrupt in [false, true]) {
+ testWidgets('文件${corrupt ? "损坏" : "被清理"}时显示提示', (tester) async {
+ final dir = Directory.systemTemp.createTempSync('copysync-preview-');
+ addTearDown(() => dir.deleteSync(recursive: true));
+ final file = File('${dir.path}/invalid.png');
+ if (corrupt) file.writeAsStringSync('not an image');
+ final state = PreviewState(file.path);
+ addTearDown(state.dispose);
+ await openPreview(tester, state);
+ for (
+ var i = 0;
+ i < 60 && find.text('无法读取图片,文件可能已被清理或损坏').evaluate().isEmpty;
+ i++
+ ) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 50)),
+ );
+ await tester.pump();
+ }
+ expect(find.text('无法读取图片,文件可能已被清理或损坏'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+ }
+}
diff --git a/ui/test/pairing_flow_test.dart b/ui/test/pairing_flow_test.dart
new file mode 100644
index 0000000..55e1752
--- /dev/null
+++ b/ui/test/pairing_flow_test.dart
@@ -0,0 +1,163 @@
+import 'dart:async';
+
+import 'package:copysync_ui/app_state.dart';
+import 'package:copysync_ui/gen/copysync/v1/daemon.pb.dart';
+import 'package:copysync_ui/main.dart';
+import 'package:copysync_ui/widgets/pairing_dialog.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+Device pendingPeer([String session = 'session-1']) => Device(
+ id: 'peer',
+ name: '另一台电脑',
+ publicKeyFingerprint: 'BBBB-CCCC-DDDD',
+ pairingSession: session,
+);
+
+class PairingState extends AppState {
+ final redemption = Completer<Device>();
+ final confirmations = <(String, bool)>[];
+ bool failConfirmation = false;
+
+ PairingState() {
+ debugSeed(
+ status: Status(signalingConnected: true),
+ config: Config(),
+ self: Device(
+ id: 'self',
+ name: '本机',
+ publicKeyFingerprint: 'AAAA-BBBB-CCCC',
+ ),
+ );
+ }
+
+ void receive(Device peer) => debugEvent(Event(deviceChanged: peer));
+
+ @override
+ Future<String> createPairingCode() async => 'ABC123';
+
+ @override
+ Future<Device> redeemPairingCode(String code) async {
+ final peer = await redemption.future;
+ receive(peer);
+ return peer;
+ }
+
+ @override
+ Future<void> confirmPairing(String session, bool accept) async {
+ confirmations.add((session, accept));
+ if (failConfirmation) throw StateError('配对会话已过期');
+ dismissPendingPairing(session);
+ if (accept) receive(pendingPeer()..clearPairingSession());
+ }
+}
+
+Future<void> openSetup(WidgetTester tester, PairingState state) async {
+ await tester.pumpWidget(CopySyncApp(state: state));
+ await tester.tap(find.text('设备').first);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('添加设备').first);
+ await tester.pumpAndSettle();
+}
+
+void expectSingleConfirmation() {
+ // 包括被第二个对话框盖住的路由,避免只检查最上层而漏掉叠加弹窗。
+ expect(
+ find.byType(PairingConfirmDialog, skipOffstage: false),
+ findsOneWidget,
+ );
+ expect(find.byType(PairingDialog, skipOffstage: false), findsNothing);
+}
+
+void main() {
+ for (final eventFirst in [false, true]) {
+ testWidgets('输入配对码只确认一次,${eventFirst ? "事件先到、RPC 迟到" : "RPC 先到、事件重复"}', (
+ tester,
+ ) async {
+ final state = PairingState();
+ addTearDown(state.dispose);
+ await openSetup(tester, state);
+ await tester.tap(find.text('输入配对码'));
+ await tester.pumpAndSettle();
+ await tester.enterText(find.byType(TextField), 'ABC123');
+ await tester.tap(find.text('继续'));
+ if (eventFirst) {
+ state.receive(pendingPeer());
+ } else {
+ state.redemption.complete(pendingPeer());
+ }
+ await tester.pumpAndSettle();
+ expectSingleConfirmation();
+
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expectSingleConfirmation();
+ await tester.tap(find.text('一致,确认配对'));
+ await tester.pumpAndSettle();
+
+ // 用户可能在兑换 RPC 返回前就通过事件弹出的确认框完成了配对。
+ if (eventFirst) state.redemption.complete(pendingPeer());
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expect(state.confirmations, [('session-1', true)]);
+ expect(state.pendingPairing, isNull);
+ expect(
+ find.byType(PairingConfirmDialog, skipOffstage: false),
+ findsNothing,
+ );
+ expect(find.byType(PairingDialog, skipOffstage: false), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ for (final accept in [false, true]) {
+ testWidgets('生成配对码后${accept ? "接受" : "拒绝"}请求,移除旧页面且不再次弹窗', (tester) async {
+ final state = PairingState();
+ addTearDown(state.dispose);
+ await openSetup(tester, state);
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expectSingleConfirmation();
+ await tester.tap(find.text(accept ? '一致,确认配对' : '不一致,拒绝'));
+ await tester.pumpAndSettle();
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expect(state.confirmations, [('session-1', accept)]);
+ expect(
+ find.byType(PairingConfirmDialog, skipOffstage: false),
+ findsNothing,
+ );
+ expect(find.byType(PairingDialog, skipOffstage: false), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ testWidgets('未打开添加设备时收到请求仍主动确认,过期后不会反复弹出', (tester) async {
+ final state = PairingState()..failConfirmation = true;
+ addTearDown(state.dispose);
+ await tester.pumpWidget(CopySyncApp(state: state));
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expectSingleConfirmation();
+ await tester.tap(find.text('一致,确认配对'));
+ await tester.pumpAndSettle();
+ state.receive(pendingPeer());
+ await tester.pumpAndSettle();
+ expect(
+ find.byType(PairingConfirmDialog, skipOffstage: false),
+ findsNothing,
+ );
+ expect(state.pendingPairing, isNull);
+ expect(tester.takeException(), isNull);
+ });
+
+ test('处理旧会话不清掉新的配对请求', () {
+ final state = PairingState();
+ addTearDown(state.dispose);
+ state.receive(pendingPeer());
+ state.receive(pendingPeer('session-2'));
+ state.dismissPendingPairing('session-1');
+ state.receive(pendingPeer());
+ expect(state.pendingPairing?.pairingSession, 'session-2');
+ });
+}