| 1 | using System.Collections.Specialized; |
| 2 | using System.Runtime.InteropServices; |
| 3 | using System.Text.Json; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | internal static class SharedClipboard |
| 8 | { |
| 9 | private static int generation; |
| 10 | private static readonly Dictionary<string, string[]> copies = new(); |
| 11 | private static readonly List<string[]> readers = new(); |
| 12 | private static readonly HashSet<string> pending = new(); |
| 13 | private static readonly System.Windows.Forms.Timer timer = new() { Interval = 1000 }; |
| 14 | private static bool watching, loaded, collecting; |
| 15 | |
| 16 | public static void Cancel() => generation++; |
| 17 | [DllImport("user32.dll")] |
| 18 | private static extern uint GetClipboardSequenceNumber(); |
| 19 | public static uint Revision |
| 20 | { |
| 21 | get |
| 22 | { |
| 23 | if (!watching) |
| 24 | { |
| 25 | watching = true; |
| 26 | timer.Tick += async (_, _) => await Collect(); |
| 27 | timer.Start(); |
| 28 | } |
| 29 | return GetClipboardSequenceNumber(); |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | private static async Task<JsonElement> Cache(string action, string id = "") |
| 34 | { |
| 35 | var request = JsonSerializer.Serialize(new { action, cache_id = id }); |
| 36 | var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10), outputLimit: 30 << 20); |
| 37 | if (result.Exit != 0) throw new IOException("clipboard_cache_operation_failed"); |
| 38 | return result.Data; |
| 39 | } |
| 40 | |
| 41 | private static bool References(string[] selected, string[] owned) |
| 42 | { |
| 43 | var root = Path.GetDirectoryName(owned[0])!; |
| 44 | return selected.Any(path => Path.GetFullPath(path).Equals(root, StringComparison.OrdinalIgnoreCase) |
| 45 | || Path.GetFullPath(path).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) |
| 46 | || root.StartsWith(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)); |
| 47 | } |
| 48 | |
| 49 | private static async Task ReleaseLocal(string id) |
| 50 | { |
| 51 | try { await Cache("release", id); copies.Remove(id); } |
| 52 | catch { } |
| 53 | } |
| 54 | |
| 55 | private static async Task Collect() |
| 56 | { |
| 57 | if (collecting) return; |
| 58 | collecting = true; |
| 59 | try |
| 60 | { |
| 61 | if (!loaded) |
| 62 | { |
| 63 | var result = await Cache("list"); |
| 64 | foreach (var item in result.GetProperty("selections").EnumerateArray()) |
| 65 | copies.TryAdd(item.Text("cache_id"), item.GetProperty("paths").EnumerateArray().Select(path => path.GetString()!).ToArray()); |
| 66 | loaded = true; |
| 67 | } |
| 68 | foreach (var copy in copies.ToArray()) |
| 69 | { |
| 70 | var selected = Clipboard.ContainsFileDropList() ? Clipboard.GetFileDropList().Cast<string>().ToArray() : []; |
| 71 | if (pending.Contains(copy.Key) || References(selected, copy.Value) || readers.Any(paths => References(paths, copy.Value))) continue; |
| 72 | await ReleaseLocal(copy.Key); |
| 73 | } |
| 74 | } |
| 75 | catch { } |
| 76 | finally { collecting = false; } |
| 77 | } |
| 78 | |
| 79 | private static async Task ReleaseRemote(string connection, string id, CancellationToken token) |
| 80 | { |
| 81 | var response = await Backend.Json(["clipboard-files", "--json", "--connection", connection, "release", id], token, TimeSpan.FromSeconds(10)); |
| 82 | if (response.Exit != 0) throw new IOException("clipboard_selection_release_failed"); |
| 83 | } |
| 84 | |
| 85 | public static async Task<object> Release(JsonElement request, CancellationToken token) |
| 86 | { |
| 87 | var id = request.Text("files"); |
| 88 | if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效"); |
| 89 | await ReleaseRemote(request.Text("connection_id"), id, token); |
| 90 | return new { ok = true }; |
| 91 | } |
| 92 | |
| 93 | public static async Task<object> Read(JsonElement request, CancellationToken token) |
| 94 | { |
| 95 | var revision = Revision; |
| 96 | var capturedGeneration = generation; |
| 97 | if (Clipboard.ContainsFileDropList()) |
| 98 | { |
| 99 | var selected = Clipboard.GetFileDropList().Cast<string>().ToArray(); |
| 100 | readers.Add(selected); |
| 101 | try |
| 102 | { |
| 103 | var arguments = new List<string> { "clipboard-files", "--json", "--connection", request.Text("connection_id"), "send" }; |
| 104 | arguments.AddRange(selected); |
| 105 | var response = await Backend.Json(arguments.ToArray(), token, TimeSpan.FromMinutes(30)); |
| 106 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 107 | var files = response.Data.Text("files"); |
| 108 | if (capturedGeneration != generation || revision != Revision) |
| 109 | { |
| 110 | try { await ReleaseRemote(request.Text("connection_id"), files, CancellationToken.None); } catch { } |
| 111 | } |
| 112 | return new { revision, files }; |
| 113 | } |
| 114 | finally { readers.Remove(selected); await Collect(); } |
| 115 | } |
| 116 | if (Clipboard.ContainsImage()) |
| 117 | { |
| 118 | using var image = Clipboard.GetImage() ?? throw new IOException("无法读取剪贴板图片"); |
| 119 | if ((long)image.Width * image.Height > 40_000_000) throw new IOException("图片不能超过 4000 万像素"); |
| 120 | using var output = new MemoryStream(); |
| 121 | image.Save(output, System.Drawing.Imaging.ImageFormat.Png); |
| 122 | if (output.Length > 20 * 1024 * 1024) throw new IOException("图片不能超过 20 MB"); |
| 123 | return new { revision, png = Convert.ToBase64String(output.ToArray()) }; |
| 124 | } |
| 125 | return new { revision, text = Clipboard.ContainsText() ? Clipboard.GetText() : "" }; |
| 126 | } |
| 127 | |
| 128 | public static async Task<object> Write(JsonElement request, CancellationToken token) |
| 129 | { |
| 130 | _ = Revision; |
| 131 | var currentGeneration = generation; |
| 132 | string[]? paths = null; |
| 133 | var cache = ""; |
| 134 | if (request.Text("files") is { Length: > 0 } id) |
| 135 | { |
| 136 | if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效"); |
| 137 | try |
| 138 | { |
| 139 | var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30)); |
| 140 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 141 | paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray(); |
| 142 | cache = response.Data.Text("cache_id"); |
| 143 | if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); } |
| 144 | } |
| 145 | catch { loaded = false; throw; } |
| 146 | } |
| 147 | try |
| 148 | { |
| 149 | if (currentGeneration != generation || request.TryGetProperty("revision", out var expected) && expected.GetUInt32() != Revision) |
| 150 | { |
| 151 | if (cache.Length != 0) await ReleaseLocal(cache); |
| 152 | return new { revision = Revision, superseded = true }; |
| 153 | } |
| 154 | if (paths != null) |
| 155 | { |
| 156 | var files = new StringCollection(); files.AddRange(paths); Clipboard.SetFileDropList(files); |
| 157 | } |
| 158 | else if (request.Text("png") is { Length: > 0 } png) |
| 159 | { |
| 160 | var bytes = Convert.FromBase64String(png); |
| 161 | if (bytes.Length > 20 * 1024 * 1024) throw new InvalidDataException("图片不能超过 20 MB"); |
| 162 | using var input = new MemoryStream(bytes); |
| 163 | using var image = Image.FromStream(input); |
| 164 | if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("图片不能超过 4000 万像素"); |
| 165 | Clipboard.SetImage(image); |
| 166 | } |
| 167 | else if (request.TryGetProperty("text", out var text)) |
| 168 | { |
| 169 | var value = text.GetString() ?? ""; |
| 170 | if (System.Text.Encoding.UTF8.GetByteCount(value) > 2 * 1024 * 1024) throw new InvalidDataException("文本不能超过 2 MB"); |
| 171 | if (value.Length == 0) Clipboard.Clear(); else Clipboard.SetText(value); |
| 172 | } |
| 173 | else throw new InvalidDataException("剪贴板格式无效"); |
| 174 | var writtenRevision = Revision; |
| 175 | if (cache.Length != 0) { try { await Cache("publish", cache); } catch { } } |
| 176 | return new { revision = writtenRevision }; |
| 177 | } |
| 178 | finally { pending.Remove(cache); await Collect(); } |
| 179 | } |
| 180 | } |