PasteFerry (隔空贴): clipboard and file sync across macOS, Windows and Linux. Direct-first, end-to-end encrypted. Optional official access: no server to host. Independent self-hosting remains available.
Dart airdrop-alternativeclipboardclipboard-sharingclipboard-synccopy-pastecross-platformend-to-end-encryptionfile-syncfile-transferfluttergolanglinuxmacosnat-traversalp2pself-hostedtailscaleuniversal-clipboardwebrtcwindows
Windows 界面、构建与安装程序
baiyuze71bc50c5b029
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a1ca5b9..800865b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -4,6 +4,8 @@ on:push:branches: [main]pull_request:+ # 手动运行:开发中的分支(比如 windows)不必合进 main 也能跑一遍+ workflow_dispatch:jobs:server:@@ -56,3 +58,34 @@ jobs:- run: CGO_ENABLED=0 go build -o /tmp/natlab ./cmd/natlabworking-directory: client-core- run: sudo bash tools/natlab/run.sh /tmp/natlab++ windows:+ name: Windows 客户端+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: client-core/go.mod+ cache-dependency-path: client-core/go.sum+ - run: go vet ./... ; if ($LASTEXITCODE) { exit 1 } ; go test ./...+ working-directory: client-core+ - uses: subosito/flutter-action@v2+ with:+ channel: stable+ cache: true+ - run: flutter pub get ; flutter analyze ; if ($LASTEXITCODE) { exit 1 } ; flutter test+ working-directory: ui+ - name: 安装 Inno Setup+ run: |+ if (-not (Test-Path "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe")) {+ choco install innosetup -y --no-progress+ }+ - run: powershell -ExecutionPolicy Bypass -File scripts\build-windows.ps1+ # 构建好的安装包与便携版留作下载,方便在真机上试+ - uses: actions/upload-artifact@v4+ with:+ name: CopySync-windows+ path: |+ dist/windows/CopySync-Setup.exe+ dist/windows/CopySync-windows-x64.zipdiff --git a/client-core/internal/pack/names_test.go b/client-core/internal/pack/names_test.goindex fe69ff4..6edfa26 100644--- a/client-core/internal/pack/names_test.go+++ b/client-core/internal/pack/names_test.go@@ -6,6 +6,7 @@ import ("io""os""path/filepath"+ "runtime""sort""testing"@@ -87,8 +88,9 @@ func writeTar(t *testing.T, entries []tar.Header, bodies map[string]string) io.R}func TestUnpackForWindows(t *testing.T) {+ old := windowsNameswindowsNames = true- t.Cleanup(func() { windowsNames = false })+ t.Cleanup(func() { windowsNames = old })r := writeTar(t, []tar.Header{{Name: "会议:纪要/", Typeflag: tar.TypeDir, Mode: 0o755},@@ -136,6 +138,9 @@ func TestUnpackForWindows(t *testing.T) {// 打不开的文件要整个跳过,不能写了头却没有内容,把整个归档弄坏。func TestPackSkipsUnreadableFile(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("Windows 上权限位挡不住读取,造不出打不开的文件")+ }if os.Geteuid() == 0 {t.Skip("root 能读任何文件")}diff --git a/scripts/build-windows.ps1 b/scripts/build-windows.ps1new file mode 100644index 0000000..3f0bd20--- /dev/null+++ b/scripts/build-windows.ps1@@ -0,0 +1,72 @@+# 在 Windows 上构建 CopySync,产物放在 dist\windows\:+#+# CopySync\ 可以直接运行的目录:界面、后台服务、命令行工具+# CopySync-Setup.exe 安装程序(需要 Inno Setup 6)+# CopySync-windows-x64.zip 便携版+#+# powershell -ExecutionPolicy Bypass -File scripts\build-windows.ps1 [-Version 1.2.0]+#+# 需要 Go、Flutter 与 Visual Studio(「使用 C++ 的桌面开发」)。+# 后台服务是纯 Go,也可以在 Mac 上交叉编译;界面只能在 Windows 上构建。++param([string]$Version)++$ErrorActionPreference = 'Stop'+$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path+Set-Location $root++# 版本号与 Mac 版共用 scripts/build.sh 里的那一个+if (-not $Version) {+ $m = Select-String -Path scripts\build.sh -Pattern 'VERSION=\$\{VERSION:-([0-9.]+)\}'+ $Version = $m.Matches[0].Groups[1].Value+}++$out = Join-Path $root 'dist\windows'+$app = Join-Path $out 'CopySync'+if (Test-Path $out) { Remove-Item -Recurse -Force $out }+New-Item -ItemType Directory -Force $app | Out-Null++function Invoke-Checked([scriptblock]$cmd, [string]$what) {+ & $cmd+ if ($LASTEXITCODE -ne 0) { throw "$what 失败(退出码 $LASTEXITCODE)" }+}++Write-Host "▶ 构建后台服务与命令行工具($Version)"+$env:CGO_ENABLED = '0'; $env:GOOS = 'windows'; $env:GOARCH = 'amd64'+Push-Location client-core+try {+ # -H=windowsgui:后台服务没有控制台窗口,开机自启时不会闪一下黑框+ Invoke-Checked { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.version=$Version" -o "$app\copysyncd.exe" ./cmd/copysyncd } 'go build copysyncd'+ Invoke-Checked { go build -trimpath -ldflags '-s -w' -o "$app\copysync-cli.exe" ./cmd/copysync-cli } 'go build copysync-cli'+} finally {+ Pop-Location+ Remove-Item Env:CGO_ENABLED, Env:GOOS, Env:GOARCH+}++Write-Host '▶ 构建图形界面'+Push-Location ui+try {+ Invoke-Checked { flutter build windows --release --build-name $Version "--dart-define=APP_VERSION=$Version" } 'flutter build windows'+} finally {+ Pop-Location+}+Copy-Item -Recurse -Force 'ui\build\windows\x64\runner\Release\*' $app++Write-Host '▶ 打包'+Compress-Archive -Path $app -DestinationPath (Join-Path $out 'CopySync-windows-x64.zip')++$iscc = Get-Command iscc.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source+if (-not $iscc) {+ $iscc = @(+ "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",+ "$env:ProgramFiles\Inno Setup 6\ISCC.exe",+ "$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe"+ ) | Where-Object { Test-Path $_ } | Select-Object -First 1+}+if ($iscc) {+ Invoke-Checked { & $iscc /Qp "/DAppVersion=$Version" "/DSourceDir=$app" "/DOutputDir=$out" tools\installer\copysync.iss } 'Inno Setup'+} else {+ Write-Warning '没有找到 Inno Setup 6,跳过安装程序,只出便携版 zip'+}++Get-ChildItem $out -File | ForEach-Object { Write-Host " ✓ $($_.Name) $([math]::Round($_.Length / 1MB, 1)) MB" }diff --git a/tools/icon/ico.py b/tools/icon/ico.pynew file mode 100644index 0000000..9b56347--- /dev/null+++ b/tools/icon/ico.py@@ -0,0 +1,37 @@+"""把 render.swift --windows 输出的各尺寸 PNG 打包成 Windows 的 .ico。++ python3 tools/icon/ico.py <PNG 所在目录> <输出的 .ico>++每个尺寸直接以 PNG 存进 ico(Windows Vista 起支持),保留透明度,也不需要额外的库。+"""++import re+import struct+import sys+from pathlib import Path+++def main(src: Path, dst: Path) -> None:+ images = []+ for p in sorted(src.glob("windows_*.png"), key=lambda p: int(re.findall(r"\d+", p.name)[0])):+ data = p.read_bytes()+ # PNG 的 IHDR 里是宽高+ w, h = struct.unpack(">II", data[16:24])+ images.append((w, h, data))+ if not images:+ sys.exit(f"{src} 里没有 windows_*.png")++ header = struct.pack("<HHH", 0, 1, len(images)) # 保留、类型 1 = 图标、数量+ offset = len(header) + 16 * len(images)+ entries, blobs = b"", b""+ for w, h, data in images:+ # 宽高为 256 时按约定写 0+ entries += struct.pack("<BBBBHHII", w % 256, h % 256, 0, 0, 1, 32, len(data), offset)+ blobs += data+ offset += len(data)+ dst.write_bytes(header + entries + blobs)+ print(f"✓ {dst}({', '.join(str(w) for w, _, _ in images)})")+++if __name__ == "__main__":+ main(Path(sys.argv[1]), Path(sys.argv[2]))diff --git a/tools/icon/render.swift b/tools/icon/render.swiftindex 5b88ac9..5c40406 100644--- a/tools/icon/render.swift+++ b/tools/icon/render.swift@@ -1,6 +1,7 @@// 绘制 CopySync 的 App 图标,输出各尺寸 PNG。//// swift tools/icon/render.swift <输出目录>+// swift tools/icon/render.swift <输出目录> --windows # Windows 用:主体放大填满画布,再用 ico.py 打包//// 造型:两张错位的纸。后一张描边、前一张实色,表示「这台复制、那台出现」。// 网站用的 tools/icon/icon.svg 与这里的几何参数一一对应,改动时两边同步。@@ -83,7 +84,9 @@ func lines(in ctx: CGContext, sheet: CGRect, color: NSColor) {}}-func render(size: Int, to url: URL) throws {+/// crop 是 1024 画布上要铺满输出图片的区域。macOS 用整张画布;Windows 的图标+/// 不留 Apple 网格那一圈阴影空间,只留一点边,否则在任务栏和开始菜单里显得偏小。+func render(size: Int, to url: URL, crop: CGFloat = 0) throws {let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: size, pixelsHigh: size,bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true,isPlanar: false, colorSpaceName: .deviceRGB,@@ -92,7 +95,9 @@ func render(size: Int, to url: URL) throws {let ctx = gctx.cgContextctx.interpolationQuality = .highctx.setShouldAntialias(true)- ctx.scaleBy(x: CGFloat(size) / 1024, y: CGFloat(size) / 1024)+ let span = 1024 - 2 * crop+ ctx.scaleBy(x: CGFloat(size) / span, y: CGFloat(size) / span)+ ctx.translateBy(x: -crop, y: -crop)draw(in: ctx)gctx.flushGraphics()guard let png = rep.representation(using: .png, properties: [:]) else {@@ -101,9 +106,17 @@ func render(size: Int, to url: URL) throws {try png.write(to: url)}-let out = URL(fileURLWithPath: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : ".")+let args = CommandLine.arguments.dropFirst()+let out = URL(fileURLWithPath: args.first { !$0.hasPrefix("--") } ?? ".")try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)-for size in [16, 32, 64, 128, 180, 256, 512, 1024] {- try render(size: size, to: out.appendingPathComponent("icon_\(size).png"))+if args.contains("--windows") {+ // 主体 824 居中(100…924),四周各留 28 给投影:主体占画布的 94%+ for size in [16, 20, 24, 32, 40, 48, 64, 128, 256] {+ try render(size: size, to: out.appendingPathComponent("windows_\(size).png"), crop: 72)+ }+} else {+ for size in [16, 32, 64, 128, 180, 256, 512, 1024] {+ try render(size: size, to: out.appendingPathComponent("icon_\(size).png"))+ }}print("✓ \(out.path)")diff --git a/tools/installer/copysync.iss b/tools/installer/copysync.issnew file mode 100644index 0000000..3277ceb--- /dev/null+++ b/tools/installer/copysync.iss@@ -0,0 +1,97 @@+; 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;diff --git a/ui/lib/background_service.dart b/ui/lib/background_service.dartindex 872b606..cbe4194 100644--- a/ui/lib/background_service.dart+++ b/ui/lib/background_service.dart@@ -1,5 +1,7 @@import 'dart:io';+import 'background_service_windows.dart';+/// 构建时注入的版本号(build.sh 传 --dart-define=APP_VERSION)。/// 用来判断后台服务是不是跟界面同一个版本。const appVersion = String.fromEnvironment('APP_VERSION', defaultValue: 'dev');@@ -9,8 +11,9 @@ enum ServiceState {/// 开发构建:App 包里没有内置后台服务,只能用源码目录的脚本安装unavailable,- /// 直接从 DMG 里打开、或被系统随机化路径(App Translocation)运行:- /// 这时注册的登录项会指向一个随时消失的路径,必须先把 App 移到「应用程序」+ /// 从一个随时会消失的位置运行,这时登记的自启项会指向不存在的路径:+ /// Mac 上是直接从 DMG 里打开、或被系统随机化路径(App Translocation);+ /// Windows 上是直接在压缩包里双击打开(实际运行在临时目录)mustMove,/// 尚未注册为登录项@@ -25,13 +28,36 @@ enum ServiceState {running,}-/// 管理随 App 一起分发的后台服务(剪贴板监听与同步进程)。-///-/// 后台服务内置在 `CopySync.app/Contents/Helpers/` 下,由界面在首次启动时-/// 注册成 launchd 的 LaunchAgent:开机自启、崩溃自动拉起,关掉窗口也照常同步。+/// 管理随 App 一起分发的后台服务(剪贴板监听与同步进程):开机自启、崩溃自动拉起,+/// 关掉窗口也照常同步。各平台的做法不同,见 [MacBackgroundService] 与+/// [WindowsBackgroundService]。+abstract class BackgroundService {+ factory BackgroundService() =>+ Platform.isWindows ? WindowsBackgroundService() : MacBackgroundService();++ /// App 里是否带着后台服务(开发构建没有)+ bool get available;++ /// 运行日志的位置,显示给用户看的写法+ String get displayLogPath;++ Future<ServiceState> state();++ /// 注册并启动。重复调用即为修复。+ Future<void> install();++ /// 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。+ Future<void> restart();++ /// 停用并取消开机自启。数据目录保留,重新启用后历史记录与配对关系都还在。+ Future<void> uninstall();+}++/// Mac:后台服务内置在 `CopySync.app/Contents/Helpers/` 下,由界面在首次启动时+/// 注册成 launchd 的 LaunchAgent。/// 用 LaunchAgent 而非 LaunchDaemon:剪贴板属于登录用户的会话,系统级进程访问不到。-class BackgroundService {- BackgroundService({String? executable, String? home})+class MacBackgroundService implements BackgroundService {+ MacBackgroundService({String? executable, String? home}): _executable = executable ?? Platform.resolvedExecutable,_home = home ?? Platform.environment['HOME'] ?? '';@@ -48,14 +74,19 @@ class BackgroundService {String get plistPath => '$_home/Library/LaunchAgents/$label.plist';String get logPath => '$_home/Library/Logs/CopySync/daemon.log';+ @override+ String get displayLogPath => logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~');+/// 旧版 install.sh 装在这里,迁移时清理掉String get _legacyApp => '$_home/Applications/CopySyncDaemon.app';+ @overridebool get available => Platform.isMacOS && File(helperBinary).existsSync();bool get _runningFromTemporaryLocation =>_bundle.startsWith('/Volumes/') || _bundle.contains('/AppTranslocation/');+ @overrideFuture<ServiceState> state() async {if (!available) return ServiceState.unavailable;if (_runningFromTemporaryLocation) return ServiceState.mustMove;@@ -70,6 +101,7 @@ class BackgroundService {}/// 注册并启动。重复调用即为修复:先注销旧的再重新注册。+ @overrideFuture<void> install() async {await _bootout();@@ -91,6 +123,7 @@ class BackgroundService {}/// 让 launchd 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。+ @overrideFuture<void> restart() async {final r = await Process.run('launchctl', ['kickstart', '-k', await _target()]);if (r.exitCode != 0) {@@ -99,6 +132,7 @@ class BackgroundService {}/// 停用并移除登录项。数据目录保留,重新启用后历史记录与配对关系都还在。+ @overrideFuture<void> uninstall() async {await _bootout();final plist = File(plistPath);diff --git a/ui/lib/background_service_windows.dart b/ui/lib/background_service_windows.dartnew file mode 100644index 0000000..2e69a72--- /dev/null+++ b/ui/lib/background_service_windows.dart@@ -0,0 +1,113 @@+import 'dart:io';++import 'background_service.dart';++/// Windows:后台服务 `copysyncd.exe` 与 `CopySync.exe` 放在同一个目录。+///+/// 开机自启登记在 `HKCU\...\Run`,只影响当前用户,不需要管理员权限。登记的命令是+/// `copysyncd.exe -supervise`:守护进程拉起真正干活的子进程,子进程崩溃就隔 10 秒+/// 再拉起,相当于 Mac 上 launchd 的 KeepAlive。+///+/// 不做成 Windows 服务:服务运行在会话 0,与用户桌面隔离,访问不到用户的剪贴板。+class WindowsBackgroundService implements BackgroundService {+ WindowsBackgroundService({String? executable, Map<String, String>? environment})+ : _executable = executable ?? Platform.resolvedExecutable,+ _env = environment ?? Platform.environment;++ static const _runKey = r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run';+ static const _valueName = 'CopySync';+ static const _image = 'copysyncd.exe';++ final String _executable;+ final Map<String, String> _env;++ String get daemonPath => '${File(_executable).parent.path}\\$_image';++ /// 登记到自启项里的命令行+ String get _command => '"$daemonPath" -supervise';++ String get _localAppData => _env['LOCALAPPDATA'] ?? '${_env['USERPROFILE']}\\AppData\\Local';++ String get logPath => '$_localAppData\\CopySync\\logs\\daemon.log';++ @override+ String get displayLogPath => logPath.replaceFirst(_localAppData, '%LOCALAPPDATA%');++ @override+ bool get available => Platform.isWindows && File(daemonPath).existsSync();++ /// 在资源管理器里直接双击压缩包里的程序时,它其实运行在临时目录里,+ /// 关掉之后整个目录就被删了+ bool get _runningFromTemporaryLocation {+ final temp = (_env['TEMP'] ?? '').toLowerCase();+ final exe = _executable.toLowerCase();+ return temp.isNotEmpty && exe.startsWith(temp);+ }++ @override+ Future<ServiceState> state() async {+ if (!available) return ServiceState.unavailable;+ if (_runningFromTemporaryLocation) return ServiceState.mustMove;+ final registered = await _registeredCommand();+ if (registered == null) return ServiceState.notInstalled;+ if (!registered.toLowerCase().contains(daemonPath.toLowerCase())) return ServiceState.stale;+ return await _running() ? ServiceState.running : ServiceState.stopped;+ }++ @override+ Future<void> install() async {+ final r = await Process.run('reg', [+ 'add', _runKey, '/v', _valueName, '/t', 'REG_SZ', '/d', _command, '/f', //+ ]);+ if (r.exitCode != 0) {+ throw ServiceException('登记开机自启失败:${_output(r)}');+ }+ await restart();+ }++ @override+ Future<void> restart() async {+ await _stop();+ // 脱离界面进程运行:关掉窗口后照常同步+ await Process.start(daemonPath, ['-supervise'], mode: ProcessStartMode.detached);+ }++ @override+ Future<void> uninstall() async {+ await Process.run('reg', ['delete', _runKey, '/v', _valueName, '/f']);+ await _stop();+ }++ /// 守护进程与后台服务一起结束:只结束后台服务的话,守护进程会把它重新拉起来+ Future<void> _stop() async {+ await Process.run('taskkill', ['/F', '/T', '/IM', _image]);+ for (var i = 0; i < 20 && await _running(); i++) {+ await Future<void>.delayed(const Duration(milliseconds: 250));+ }+ }++ Future<bool> _running() async {+ final r = await Process.run('tasklist', ['/FI', 'IMAGENAME eq $_image', '/NH']);+ return '${r.stdout}'.toLowerCase().contains(_image);+ }++ /// 自启项里登记的命令;没有登记时为 null。+ ///+ /// `reg query` 的输出形如:+ ///+ /// HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run+ /// CopySync REG_SZ "C:\...\copysyncd.exe" -supervise+ Future<String?> _registeredCommand() async {+ final r = await Process.run('reg', ['query', _runKey, '/v', _valueName]);+ if (r.exitCode != 0) return null;+ for (final line in '${r.stdout}'.split('\n')) {+ final i = line.indexOf('REG_SZ');+ if (line.trimLeft().startsWith(_valueName) && i >= 0) {+ return line.substring(i + 'REG_SZ'.length).trim();+ }+ }+ return null;+ }++ static String _output(ProcessResult r) => '${r.stderr}${r.stdout}'.trim();+}diff --git a/ui/lib/icons.dart b/ui/lib/icons.dartnew file mode 100644index 0000000..6348498--- /dev/null+++ b/ui/lib/icons.dart@@ -0,0 +1,43 @@+import 'dart:io';++import 'package:flutter/cupertino.dart';+import 'package:fluentui_system_icons/fluentui_system_icons.dart';++/// 界面用到的图标:Mac 上是 Cupertino 图标,Windows 上是微软的 Fluent 图标,+/// 各自与系统自带的应用一致。+abstract final class AppIcons {+ static final bool _win = Platform.isWindows;++ static IconData _pick(IconData mac, IconData windows) => _win ? windows : mac;++ static IconData get clock => _pick(CupertinoIcons.clock, FluentIcons.history_24_regular);+ static IconData get deviceLaptop => _pick(CupertinoIcons.device_laptop, FluentIcons.laptop_24_regular);+ static IconData get desktopComputer => _pick(CupertinoIcons.desktopcomputer, FluentIcons.desktop_24_regular);+ static IconData get gear => _pick(CupertinoIcons.gear, FluentIcons.settings_24_regular);+ static IconData get exclamationmarkCircle =>+ _pick(CupertinoIcons.exclamationmark_circle, FluentIcons.error_circle_24_regular);+ static IconData get trash => _pick(CupertinoIcons.trash, FluentIcons.delete_24_regular);+ static IconData get checkmark => _pick(CupertinoIcons.checkmark, FluentIcons.checkmark_24_regular);+ static IconData get checkmarkCircle =>+ _pick(CupertinoIcons.checkmark_circle, FluentIcons.checkmark_circle_24_regular);+ static IconData get xmark => _pick(CupertinoIcons.xmark, FluentIcons.dismiss_24_regular);+ static IconData get textAlignLeft =>+ _pick(CupertinoIcons.text_alignleft, FluentIcons.text_align_left_24_regular);+ static IconData get questionCircle =>+ _pick(CupertinoIcons.question_circle, FluentIcons.question_circle_24_regular);+ static IconData get plus => _pick(CupertinoIcons.plus, FluentIcons.add_24_regular);+ static IconData get photo => _pick(CupertinoIcons.photo, FluentIcons.image_24_regular);+ static IconData get lockShield => _pick(CupertinoIcons.lock_shield, FluentIcons.shield_lock_24_regular);+ static IconData get filter =>+ _pick(CupertinoIcons.line_horizontal_3_decrease, FluentIcons.filter_24_regular);+ static IconData get folder => _pick(CupertinoIcons.folder, FluentIcons.folder_24_regular);+ static IconData get ellipsis => _pick(CupertinoIcons.ellipsis, FluentIcons.more_horizontal_24_regular);+ static IconData get docRichtext =>+ _pick(CupertinoIcons.doc_richtext, FluentIcons.document_text_24_regular);+ static IconData get docOnDoc => _pick(CupertinoIcons.doc_on_doc, FluentIcons.copy_24_regular);+ static IconData get docOnClipboard =>+ _pick(CupertinoIcons.doc_on_clipboard, FluentIcons.clipboard_paste_24_regular);+ static IconData get doc => _pick(CupertinoIcons.doc, FluentIcons.document_24_regular);+ static IconData get chevronUpDown =>+ _pick(CupertinoIcons.chevron_up_chevron_down, FluentIcons.chevron_up_down_24_regular);+}diff --git a/ui/lib/main.dart b/ui/lib/main.dartindex e0aec87..e600764 100644--- a/ui/lib/main.dart+++ b/ui/lib/main.dart@@ -1,4 +1,5 @@-import 'package:flutter/cupertino.dart';+import 'dart:io';+import 'package:flutter/material.dart';import 'app_state.dart';@@ -10,6 +11,7 @@ import 'pages/settings_page.dart';import 'theme.dart';import 'widgets/common.dart';import 'widgets/pairing_dialog.dart';+import 'icons.dart';void main() => runApp(const CopySyncApp());@@ -146,8 +148,9 @@ class _Sidebar extends StatelessWidget {child: Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- // 顶部留白是 macOS 红绿灯按钮所在的标题栏- const SizedBox(height: 52),+ // Mac 上顶部留白是红绿灯按钮所在的标题栏(内容铺满了整个窗口);+ // Windows 用系统标题栏,内容从标题栏下面开始+ SizedBox(height: Platform.isMacOS ? 52 : Insets.lg),Padding(padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.lg),child: Row(@@ -159,20 +162,20 @@ class _Sidebar extends StatelessWidget {),),_NavItem(- icon: CupertinoIcons.clock,+ icon: AppIcons.clock,label: '复制记录',selected: current == Section.history,trailing: state.records.isEmpty ? null : '${state.records.length}',onTap: () => onSelect(Section.history),),_NavItem(- icon: CupertinoIcons.device_laptop,+ icon: AppIcons.deviceLaptop,label: '设备',selected: current == Section.devices,onTap: () => onSelect(Section.devices),),_NavItem(- icon: CupertinoIcons.gear,+ icon: AppIcons.gear,label: '设置',selected: current == Section.settings,onTap: () => onSelect(Section.settings),diff --git a/ui/lib/pages/devices_page.dart b/ui/lib/pages/devices_page.dartindex c82f318..b070166 100644--- a/ui/lib/pages/devices_page.dart+++ b/ui/lib/pages/devices_page.dart@@ -1,4 +1,3 @@-import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -8,6 +7,8 @@ import '../main.dart';import '../theme.dart';import '../widgets/common.dart';import '../widgets/pairing_dialog.dart';+import '../icons.dart';+import '../platform.dart';class DevicesPage extends StatelessWidget {const DevicesPage({super.key});@@ -28,7 +29,7 @@ class DevicesPage extends StatelessWidget {actions: [FilledButton.icon(onPressed: canPair ? () => _startPairing(context) : null,- icon: const Icon(CupertinoIcons.plus, size: 14),+ icon: Icon(AppIcons.plus, size: 14),label: const Text('添加设备'),),],@@ -39,15 +40,15 @@ class DevicesPage extends StatelessWidget {children: [if (state.self != null)GroupSection(- title: '这台 Mac',- footnote: '配对时,两台 Mac 会显示同样的两行安全指纹:这台的和对方的。逐字核对一致才能确认。',+ title: Wording.thisDevice,+ footnote: '配对时,${Wording.bothDevicesInText}会显示同样的两行安全指纹:这台的和对方的。逐字核对一致才能确认。',child: GroupBox(children: [_DeviceRow(device: state.self!, isSelf: true)]),),if (state.peers.isEmpty)Padding(padding: const EdgeInsets.only(top: Insets.xl),child: EmptyState(- icon: CupertinoIcons.device_laptop,+ icon: AppIcons.deviceLaptop,title: '还没有配对的设备',description: canPair? '在另一台电脑上打开 CopySync,用 6 位配对码把两台连起来。'@@ -136,8 +137,8 @@ String connectionLabel(Device d) => switch (d.connection) {};IconData platformIcon(String platform) => switch (platform) {- 'windows' => CupertinoIcons.desktopcomputer,- _ => CupertinoIcons.device_laptop,+ 'windows' => AppIcons.desktopComputer,+ _ => AppIcons.deviceLaptop,};class _DeviceMenu extends StatelessWidget {@@ -160,8 +161,8 @@ class _DeviceMenu extends StatelessWidget {),],onSelected: (v) => v == 'copy' ? _copy(context) : _unpair(context),- child: const IgnorePointer(- child: IconAction(icon: CupertinoIcons.ellipsis, tooltip: ''),+ child: IgnorePointer(+ child: IconAction(icon: AppIcons.ellipsis, tooltip: ''),),);}diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dartindex abdb88a..4daa76c 100644--- a/ui/lib/pages/history_page.dart+++ b/ui/lib/pages/history_page.dart@@ -1,4 +1,3 @@-import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import '../app_state.dart';@@ -6,6 +5,8 @@ import '../gen/copysync/v1/daemon.pb.dart';import '../main.dart';import '../theme.dart';import '../widgets/common.dart';+import '../icons.dart';+import '../platform.dart';enum _Filter { all, text, image, file }@@ -55,7 +56,7 @@ class _HistoryPageState extends State<HistoryPage> {onChanged: (f) => setState(() => _filter = f),),IconAction(- icon: CupertinoIcons.trash,+ icon: AppIcons.trash,tooltip: '清空记录',onTap: () => _confirmClear(context, state),),@@ -71,8 +72,8 @@ class _HistoryPageState extends State<HistoryPage> {child: records.isEmpty? EmptyState(icon: _filter == _Filter.all- ? CupertinoIcons.doc_on_clipboard- : CupertinoIcons.line_horizontal_3_decrease,+ ? AppIcons.docOnClipboard+ : AppIcons.filter,title: _filter == _Filter.all ? '还没有记录' : '没有这一类的记录',description: _filter == _Filter.all? '在任意一台已配对的设备上复制文本、图片或文件,记录会出现在这里。'@@ -118,7 +119,7 @@ class _HistoryPageState extends State<HistoryPage> {context: context,builder: (ctx) => AlertDialog(title: const Text('清空全部记录?'),- content: const Text('所有设备上同步来的记录和已缓存的文件都会从这台 Mac 上删除。原始文件不受影响。'),+ content: Text('所有设备上同步来的记录和已缓存的文件都会从${Wording.thisDeviceInText}上删除。原始文件不受影响。'),actions: [OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),FilledButton(@@ -276,7 +277,7 @@ class _RecordRowState extends State<_RecordRow> {child: const Text('放入剪贴板'),),IconAction(- icon: CupertinoIcons.trash,+ icon: AppIcons.trash,tooltip: '删除这条记录',onTap: () => _run(() => AppScope.read(context).deleteRecords(ids: [r.id]), '已删除'),),@@ -300,14 +301,14 @@ class _RecordRowState extends State<_RecordRow> {/// 按内容类型区分的图标:只靠形状区分,不靠颜色。IconData kindIcon(ClipRecord r) => switch (r.kind) {- ClipKind.CLIP_KIND_TEXT => CupertinoIcons.text_alignleft,- ClipKind.CLIP_KIND_HTML => CupertinoIcons.doc_richtext,- ClipKind.CLIP_KIND_IMAGE => CupertinoIcons.photo,- ClipKind.CLIP_KIND_FILE when r.items.length > 1 => CupertinoIcons.doc_on_doc,+ ClipKind.CLIP_KIND_TEXT => AppIcons.textAlignLeft,+ ClipKind.CLIP_KIND_HTML => AppIcons.docRichtext,+ ClipKind.CLIP_KIND_IMAGE => AppIcons.photo,+ ClipKind.CLIP_KIND_FILE when r.items.length > 1 => AppIcons.docOnDoc,ClipKind.CLIP_KIND_FILE when r.items.isNotEmpty && r.items.first.isDir =>- CupertinoIcons.folder,- ClipKind.CLIP_KIND_FILE => CupertinoIcons.doc,- _ => CupertinoIcons.question_circle,+ AppIcons.folder,+ ClipKind.CLIP_KIND_FILE => AppIcons.doc,+ _ => AppIcons.questionCircle,};String recordTitle(ClipRecord r) {diff --git a/ui/lib/pages/service_page.dart b/ui/lib/pages/service_page.dartindex b84127a..6123fd7 100644--- a/ui/lib/pages/service_page.dart+++ b/ui/lib/pages/service_page.dart@@ -1,3 +1,5 @@+import 'dart:io';+import 'package:flutter/material.dart';import '../app_state.dart';@@ -38,7 +40,14 @@ class _ServicePageState extends State<ServicePage> {@overrideWidget build(BuildContext context) {final state = AppScope.of(context);+ final windows = Platform.isWindows;final (title, body, button) = switch (state.serviceState) {+ ServiceState.mustMove when windows => (+ '先解压或安装 CopySync',+ 'CopySync 现在是直接从压缩包里打开的,关掉之后它所在的临时文件夹就会被删除。'+ '运行安装程序,或者把整个文件夹解压出来再打开,就可以启用后台同步。',+ null,+ ),ServiceState.mustMove => ('先把 CopySync 移到「应用程序」','CopySync 现在是直接从安装盘里打开的。把它拖进「应用程序」文件夹,'@@ -53,8 +62,11 @@ class _ServicePageState extends State<ServicePage> {),ServiceState.stale => ('重新启用后台同步',- 'CopySync 换了位置,或者之前用旧版安装脚本装过。重新启用一次,'- '让后台进程指向当前这个 App。历史记录与配对关系都会保留。',+ windows+ ? 'CopySync 换了位置,开机自启还指向原来的地方。重新启用一次,'+ '让后台进程指向当前这份 CopySync。历史记录与配对关系都会保留。'+ : 'CopySync 换了位置,或者之前用旧版安装脚本装过。重新启用一次,'+ '让后台进程指向当前这个 App。历史记录与配对关系都会保留。','重新启用',),ServiceState.stopped => (@@ -65,8 +77,11 @@ class _ServicePageState extends State<ServicePage> {),_ => ('后台服务没有运行',- '这是开发构建,App 里没有内置后台服务。'- '在源码目录运行 ./scripts/install-macos.sh 安装它。',+ windows+ ? '这是开发构建,旁边没有 copysyncd.exe。'+ '在源码目录运行 scripts\\build-windows.ps1 构建完整的版本。'+ : '这是开发构建,App 里没有内置后台服务。'+ '在源码目录运行 ./scripts/install-macos.sh 安装它。',null,),};@@ -103,7 +118,7 @@ class _ServicePageState extends State<ServicePage> {const SizedBox(height: Insets.xl),Text(state.serviceState == ServiceState.stopped- ? '运行日志:${state.service.logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~')}'+ ? '运行日志:${state.service.displayLogPath}': '随时可以在「设置」中停用后台同步。',style: context.text.bodySmall,),diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dartindex 9f30f6f..0c13212 100644--- a/ui/lib/pages/settings_page.dart+++ b/ui/lib/pages/settings_page.dart@@ -1,7 +1,5 @@-import 'dart:io';import 'package:fixnum/fixnum.dart';-import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import '../app_state.dart';@@ -9,6 +7,8 @@ import '../gen/copysync/v1/daemon.pb.dart';import '../main.dart';import '../theme.dart';import '../widgets/common.dart';+import '../icons.dart';+import '../platform.dart';class SettingsPage extends StatefulWidget {const SettingsPage({super.key});@@ -83,7 +83,7 @@ class _SettingsPageState extends State<SettingsPage> {suffixIcon: _serverDirty? IconButton(tooltip: '保存',- icon: Icon(CupertinoIcons.checkmark, size: 14, color: p.accent),+ icon: Icon(AppIcons.checkmark, size: 14, color: p.accent),onPressed: () => _saveServer(state, cfg),): null,@@ -112,7 +112,7 @@ class _SettingsPageState extends State<SettingsPage> {]),),GroupSection(- title: '这台 Mac',+ title: Wording.thisDevice,child: GroupBox(children: [SettingRow(title: '设备名称',@@ -125,7 +125,7 @@ class _SettingsPageState extends State<SettingsPage> {suffixIcon: _nameDirty? IconButton(tooltip: '保存',- icon: Icon(CupertinoIcons.checkmark, size: 14, color: p.accent),+ icon: Icon(AppIcons.checkmark, size: 14, color: p.accent),onPressed: () => _saveName(state, cfg),): null,@@ -267,7 +267,7 @@ class _SettingsPageState extends State<SettingsPage> {);}- static void _open(String url) => Process.run('open', [url]);+ static void _open(String url) => openUrl(url);Future<void> _serviceAction(Future<void> Function() action, String message) async {try {@@ -283,7 +283,7 @@ class _SettingsPageState extends State<SettingsPage> {context: context,builder: (ctx) => AlertDialog(title: const Text('停用后台同步?'),- content: const Text('这台 Mac 将停止同步,也不再开机启动。历史记录和配对关系会保留。'),+ content: Text('${Wording.thisDeviceInText}将停止同步,也不再开机启动。历史记录和配对关系会保留。'),actions: [OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('取消')),FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('停用')),@@ -433,7 +433,7 @@ class _Dropdown<T> extends StatelessWidget {children: [Text(current.value, style: context.text.labelLarge),const SizedBox(width: 6),- Icon(CupertinoIcons.chevron_up_chevron_down, size: 12, color: p.textDim),+ Icon(AppIcons.chevronUpDown, size: 12, color: p.textDim),],),),diff --git a/ui/lib/platform.dart b/ui/lib/platform.dartnew file mode 100644index 0000000..f68d536--- /dev/null+++ b/ui/lib/platform.dart@@ -0,0 +1,25 @@+import 'dart:io';++/// 随平台变化的叫法。Mac 上保持原来的文案。+abstract final class Wording {+ static final bool _win = Platform.isWindows;++ /// 说到本机时的叫法,用作标题+ static String get thisDevice => _win ? '这台电脑' : '这台 Mac';++ /// 用在句子中间:后面紧跟汉字,Mac 上要在「Mac」后留一个空格+ static String get thisDeviceInText => _win ? '这台电脑' : '这台 Mac ';++ /// 说到配对双方时的叫法,用在句子中间:Windows 上对方可能是 Mac,也可能是另一台电脑+ static String get bothDevicesInText => _win ? '两台设备' : '两台 Mac ';+}++/// 用默认浏览器打开网址。+void openUrl(String url) {+ if (Platform.isWindows) {+ // explorer 把网址交给默认浏览器;不经 cmd /c start,免得网址里的 & 被当成命令分隔符+ Process.run('explorer.exe', [url]);+ } else {+ Process.run('open', [url]);+ }+}diff --git a/ui/lib/widgets/common.dart b/ui/lib/widgets/common.dartindex 2970f74..6699e34 100644--- a/ui/lib/widgets/common.dart+++ b/ui/lib/widgets/common.dart@@ -1,7 +1,7 @@-import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import '../theme.dart';+import '../icons.dart';/// 页面统一的标题区。保证各页视觉节奏一致。class PageHeader extends StatelessWidget {@@ -266,19 +266,20 @@ class Notice extends StatelessWidget {required this.title,required this.message,this.action,- this.icon = CupertinoIcons.exclamationmark_circle,+ this.icon,this.iconColor,});final String title;final String message;final Widget? action;- final IconData icon;+ final IconData? icon;final Color? iconColor;@overrideWidget build(BuildContext context) {final p = context.palette;+ final icon = this.icon ?? AppIcons.exclamationmarkCircle;return Container(padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.md, Insets.md),decoration: BoxDecoration(@@ -422,7 +423,7 @@ void showToast(BuildContext context, String message, {bool error = false}) {content: Row(children: [Icon(- error ? CupertinoIcons.exclamationmark_circle : CupertinoIcons.checkmark_circle,+ error ? AppIcons.exclamationmarkCircle : AppIcons.checkmarkCircle,size: 16,color: error ? PaletteColors.onDark(p.danger) : PaletteColors.onDark(p.online),),diff --git a/ui/lib/widgets/pairing_dialog.dart b/ui/lib/widgets/pairing_dialog.dartindex b5e907f..7ebffa1 100644--- a/ui/lib/widgets/pairing_dialog.dart+++ b/ui/lib/widgets/pairing_dialog.dart@@ -1,4 +1,3 @@-import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';@@ -7,6 +6,8 @@ import '../gen/copysync/v1/daemon.pb.dart';import '../main.dart';import '../theme.dart';import 'common.dart';+import '../icons.dart';+import '../platform.dart';/// 配对对话框:既能生成配对码,也能输入对方的配对码。///@@ -36,7 +37,7 @@ class _PairingDialogState extends State<PairingDialog> {children: [Expanded(child: Text('添加设备', style: context.text.titleMedium)),IconAction(- icon: CupertinoIcons.xmark,+ icon: AppIcons.xmark,tooltip: '关闭',onTap: () => Navigator.pop(context),),@@ -107,7 +108,7 @@ class _GenerateTabState extends State<_GenerateTab> {return Padding(padding: const EdgeInsets.all(Insets.xl),child: EmptyState(- icon: CupertinoIcons.exclamationmark_circle,+ icon: AppIcons.exclamationmarkCircle,title: '没能生成配对码',description: _error,action: OutlinedButton(onPressed: _generate, child: const Text('重试')),@@ -156,11 +157,11 @@ class _GenerateTabState extends State<_GenerateTab> {Row(crossAxisAlignment: CrossAxisAlignment.start,children: [- Icon(CupertinoIcons.lock_shield, size: 15, color: p.textDim),+ Icon(AppIcons.lockShield, size: 15, color: p.textDim),const SizedBox(width: Insets.sm),Expanded(child: Text(- '对方输入后,两台 Mac 会显示同样的两行安全指纹,核对一致再确认。',+ '对方输入后,${Wording.bothDevicesInText}会显示同样的两行安全指纹,核对一致再确认。',style: context.text.bodySmall,),),@@ -374,7 +375,7 @@ class _PairingConfirmDialogState extends State<PairingConfirmDialog> {),const SizedBox(height: Insets.lg),Text(- '两台 Mac 上显示的这两行应当完全相同。'+ '${Wording.bothDevicesInText}上显示的这两行应当完全相同。''有任何一个字符不同,说明连接可能被第三方篡改,请拒绝。',style: context.text.bodySmall,),diff --git a/ui/pubspec.lock b/ui/pubspec.lockindex 254690b..e3dcf38 100644--- a/ui/pubspec.lock+++ b/ui/pubspec.lock@@ -73,6 +73,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.1.1"+ fluentui_system_icons:+ dependency: "direct main"+ description:+ name: fluentui_system_icons+ sha256: "1592ae32dae75fb66741ab2c0607bc6554ef086f1c457e27ef937fb4901d33da"+ url: "https://pub.dev"+ source: hosted+ version: "1.1.273"flutter:dependency: "direct main"description: flutterdiff --git a/ui/pubspec.yaml b/ui/pubspec.yamlindex d9a9065..d63db03 100644--- a/ui/pubspec.yaml+++ b/ui/pubspec.yaml@@ -37,6 +37,7 @@ dependencies:grpc: ^5.1.0protobuf: ^6.1.0fixnum: ^1.1.1+ fluentui_system_icons: ^1.1.273dev_dependencies:flutter_test:diff --git a/ui/windows/CMakeLists.txt b/ui/windows/CMakeLists.txtindex fa726f6..4d453eb 100644--- a/ui/windows/CMakeLists.txt+++ b/ui/windows/CMakeLists.txt@@ -4,7 +4,7 @@ project(copysync_ui LANGUAGES CXX)# The name of the executable created for the application. Change this to change# the on-disk name of your application.-set(BINARY_NAME "copysync_ui")+set(BINARY_NAME "CopySync")# Explicitly opt in to modern CMake behaviors to avoid warnings with recent# versions of CMake.diff --git a/ui/windows/runner/Runner.rc b/ui/windows/runner/Runner.rcindex 13acfc5..6a39e37 100644--- a/ui/windows/runner/Runner.rc+++ b/ui/windows/runner/Runner.rc@@ -89,13 +89,13 @@ BEGINBEGINBLOCK "040904e4"BEGIN- VALUE "CompanyName", "com.copysync" "\0"- VALUE "FileDescription", "copysync_ui" "\0"+ VALUE "CompanyName", "CopySync" "\0"+ VALUE "FileDescription", "CopySync" "\0"VALUE "FileVersion", VERSION_AS_STRING "\0"- VALUE "InternalName", "copysync_ui" "\0"- VALUE "LegalCopyright", "Copyright (C) 2026 com.copysync. All rights reserved." "\0"- VALUE "OriginalFilename", "copysync_ui.exe" "\0"- VALUE "ProductName", "copysync_ui" "\0"+ VALUE "InternalName", "CopySync" "\0"+ VALUE "LegalCopyright", "Copyright (C) 2026 baiyuze. MIT License." "\0"+ VALUE "OriginalFilename", "CopySync.exe" "\0"+ VALUE "ProductName", "CopySync" "\0"VALUE "ProductVersion", VERSION_AS_STRING "\0"ENDENDdiff --git a/ui/windows/runner/flutter_window.cpp b/ui/windows/runner/flutter_window.cppindex 955ee30..0f0ecf1 100644--- a/ui/windows/runner/flutter_window.cpp+++ b/ui/windows/runner/flutter_window.cpp@@ -1,9 +1,50 @@#include "flutter_window.h"+#include <flutter_windows.h>+#include <optional>#include "flutter/generated_plugin_registrant.h"+namespace {++// 窗口的位置与大小存在这里,下次打开时恢复,相当于 Mac 上的 setFrameAutosaveName+constexpr wchar_t kSettingsKey[] = L"Software\\CopySync";+constexpr wchar_t kPlacementValue[] = L"WindowPlacement";++// 窗口最小尺寸(逻辑像素),与 Mac 版一致+constexpr int kMinWidth = 760;+constexpr int kMinHeight = 520;++void SavePlacement(HWND hwnd) {+ WINDOWPLACEMENT placement{sizeof(WINDOWPLACEMENT)};+ if (::GetWindowPlacement(hwnd, &placement)) {+ ::RegSetKeyValueW(HKEY_CURRENT_USER, kSettingsKey, kPlacementValue,+ REG_BINARY, &placement, sizeof(placement));+ }+}++// 恢复上次的位置与大小。返回上次是否最大化;记录无效(比如那块屏幕已经拔掉了)时不恢复。+bool RestorePlacement(HWND hwnd) {+ WINDOWPLACEMENT placement{};+ DWORD size = sizeof(placement);+ if (::RegGetValueW(HKEY_CURRENT_USER, kSettingsKey, kPlacementValue,+ RRF_RT_REG_BINARY, nullptr, &placement, &size) != ERROR_SUCCESS ||+ size != sizeof(placement) || placement.length != sizeof(placement)) {+ return false;+ }+ if (!::MonitorFromRect(&placement.rcNormalPosition, MONITOR_DEFAULTTONULL)) {+ return false;+ }+ const bool maximized = placement.showCmd == SW_SHOWMAXIMIZED;+ // 只放好位置,先不显示:窗口等 Flutter 画好第一帧再显示(见 OnCreate)+ placement.showCmd = SW_HIDE;+ ::SetWindowPlacement(hwnd, &placement);+ return maximized;+}++} // namespace+FlutterWindow::FlutterWindow(const flutter::DartProject& project): project_(project) {}@@ -13,6 +54,7 @@ bool FlutterWindow::OnCreate() {if (!Win32Window::OnCreate()) {return false;}+ const bool maximized = RestorePlacement(GetHandle());RECT frame = GetClientArea();@@ -27,8 +69,11 @@ bool FlutterWindow::OnCreate() {RegisterPlugins(flutter_controller_->engine());SetChildContent(flutter_controller_->view()->GetNativeWindow());- flutter_controller_->engine()->SetNextFrameCallback([&]() {+ flutter_controller_->engine()->SetNextFrameCallback([this, maximized]() {this->Show();+ if (maximized) {+ ::ShowWindow(this->GetHandle(), SW_MAXIMIZE);+ }});// Flutter can complete the first frame before the "show window" callback is@@ -65,6 +110,17 @@ FlutterWindow::MessageHandler(HWND hwnd, UINT const message,case WM_FONTCHANGE:flutter_controller_->engine()->ReloadSystemFonts();break;+ case WM_GETMINMAXINFO: {+ const double scale =+ FlutterDesktopGetDpiForMonitor(::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST)) / 96.0;+ auto* info = reinterpret_cast<MINMAXINFO*>(lparam);+ info->ptMinTrackSize.x = static_cast<LONG>(kMinWidth * scale);+ info->ptMinTrackSize.y = static_cast<LONG>(kMinHeight * scale);+ return 0;+ }+ case WM_CLOSE:+ SavePlacement(hwnd);+ break;}return Win32Window::MessageHandler(hwnd, message, wparam, lparam);diff --git a/ui/windows/runner/main.cpp b/ui/windows/runner/main.cppindex 0083d49..6abfb76 100644--- a/ui/windows/runner/main.cpp+++ b/ui/windows/runner/main.cpp@@ -1,12 +1,28 @@#include <flutter/dart_project.h>#include <flutter/flutter_view_controller.h>+#include <flutter_windows.h>#include <windows.h>+#include <algorithm>+#include "flutter_window.h"#include "utils.h"int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,_In_ wchar_t *command_line, _In_ int show_command) {+ // 只开一个窗口:再次打开时把已有的窗口提到前面,与 Mac 上点 Dock 图标一致+ HANDLE single_instance = ::CreateMutexW(nullptr, TRUE, L"Local\\CopySync.UI");+ if (::GetLastError() == ERROR_ALREADY_EXISTS) {+ HWND existing = ::FindWindowW(L"FLUTTER_RUNNER_WIN32_WINDOW", L"CopySync");+ if (existing) {+ if (::IsIconic(existing)) {+ ::ShowWindow(existing, SW_RESTORE);+ }+ ::SetForegroundWindow(existing);+ }+ return EXIT_SUCCESS;+ }+// Attach to console when present (e.g., 'flutter run') or create a// new console when running with a debugger.if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {@@ -24,10 +40,21 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,project.set_dart_entrypoint_arguments(std::move(command_line_arguments));+ // 默认 960×640,在主屏的工作区里居中,与 Mac 版一致。+ // 之后打开时用上次关闭时的位置与大小(见 FlutterWindow::OnCreate)+ constexpr int kWidth = 960;+ constexpr int kHeight = 640;+ RECT work{};+ ::SystemParametersInfoW(SPI_GETWORKAREA, 0, &work, 0);+ const double scale =+ FlutterDesktopGetDpiForMonitor(::MonitorFromPoint({0, 0}, MONITOR_DEFAULTTOPRIMARY)) / 96.0;+ const double left = (work.left + (work.right - work.left - kWidth * scale) / 2) / scale;+ const double top = (work.top + (work.bottom - work.top - kHeight * scale) / 2) / scale;FlutterWindow window(project);- Win32Window::Point origin(10, 10);- Win32Window::Size size(1280, 720);- if (!window.Create(L"copysync_ui", origin, size)) {+ Win32Window::Point origin(static_cast<unsigned int>(std::max(0.0, left)),+ static_cast<unsigned int>(std::max(0.0, top)));+ Win32Window::Size size(kWidth, kHeight);+ if (!window.Create(L"CopySync", origin, size)) {return EXIT_FAILURE;}window.SetQuitOnClose(true);@@ -39,5 +66,6 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,}::CoUninitialize();+ ::CloseHandle(single_instance);return EXIT_SUCCESS;}diff --git a/ui/windows/runner/resources/app_icon.ico b/ui/windows/runner/resources/app_icon.icoindex c04e20c..342d8c6 100644Binary files a/ui/windows/runner/resources/app_icon.ico and b/ui/windows/runner/resources/app_icon.ico differ