using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace XFEToolBox.QuickTools; public sealed record ClipRecord(string Text, string Source, DateTime Captured, bool Pinned = false) { public string Display => (Pinned ? "★ " : "") + Text.Replace("\r", "").Replace("\n", " "); } public sealed class ClipboardHistory : IDisposable { public static ClipboardHistory Shared { get; } = new(QuickToolPaths.Data); public ObservableCollection Entries { get; } = []; public string ExcludedProcesses { get; set; } = "KeePass,KeePassXC,1Password,Bitwarden,CredentialUIBroker"; public bool Enabled { get; private set; } public string LastError { get; private set; } = ""; public event Action? Changed; private readonly string root; private HwndSource? source; private readonly DispatcherTimer retry = new() { Interval = TimeSpan.FromMilliseconds(100) }; private int attempts; public ClipboardHistory(string root) { this.root = root; retry.Tick += (_, _) => Capture(); try { string file = Path.Combine(root, "pinned-clips.bin"); if (File.Exists(file)) { if (new FileInfo(file).Length > 8 * 1024 * 1024) throw new IOException("固定片段存储过大。"); var bytes = ProtectedData.Unprotect(File.ReadAllBytes(file), null, DataProtectionScope.CurrentUser); foreach (var entry in (JsonSerializer.Deserialize(bytes) ?? []).Where(e => e.Pinned && e.Text.Length <= 65536).Take(100)) Entries.Add(entry); } string settings = Path.Combine(root, "clipboard-settings.json"); if (File.Exists(settings)) ExcludedProcesses = JsonSerializer.Deserialize(File.ReadAllText(settings)) ?? ExcludedProcesses; } catch (Exception e) { LastError = "固定片段无法读取:" + e.Message; } } public void Start() { if (Enabled) return; source = new HwndSource(new HwndSourceParameters("XFEQuickToolsClipboard") { ParentWindow = new nint(-3), WindowStyle = 0 }); source.AddHook(Hook); if (!AddClipboardFormatListener(source.Handle)) { source.Dispose(); source = null; throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } Enabled = true; Changed?.Invoke(); // Do not read clipboard content predating explicit opt-in. } public void Stop() { Enabled = false; retry.Stop(); if (source is not null) { RemoveClipboardFormatListener(source.Handle); source.RemoveHook(Hook); source.Dispose(); source = null; } Changed?.Invoke(); } private nint Hook(nint hwnd, int msg, nint w, nint l, ref bool handled) { if (msg == 0x031D && Enabled) { attempts = 0; retry.Start(); } return 0; } private void Capture() { retry.Stop(); if (!Enabled) return; try { nint owner = GetClipboardOwner(); GetWindowThreadProcessId(owner, out uint pid); if (pid == 0) return; string process; using (var p = Process.GetProcessById((int)pid)) process = p.ProcessName; if (IsExcluded(process, ExcludedProcesses)) return; var data = Clipboard.GetDataObject(); if (data is null || data.GetDataPresent("ExcludeClipboardContentFromMonitorProcessing") || DisallowedHistory(data)) return; if (!data.GetDataPresent(DataFormats.UnicodeText)) return; if (data.GetData(DataFormats.UnicodeText) is string text) Add(text, process); } catch (ExternalException) { if (++attempts < 3) retry.Start(); } catch (Exception e) { LastError = e.Message; Changed?.Invoke(); } } private static bool DisallowedHistory(IDataObject data) { if (!data.GetDataPresent("CanIncludeInClipboardHistory")) return false; object? flag = data.GetData("CanIncludeInClipboardHistory"); return flag is int value && value == 0 || flag is MemoryStream stream && stream.ToArray().Length >= 4 && BitConverter.ToInt32(stream.ToArray(), 0) == 0; } public static bool IsExcluded(string process, string list) => list.Split([',', ';', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Any(p => Path.GetFileNameWithoutExtension(p).Equals(process, StringComparison.OrdinalIgnoreCase)); public void Add(string text, string process, bool pin = false) { if (string.IsNullOrWhiteSpace(text) || text.Length > 65536) return; var snapshot = Entries.ToArray(); var previous = Entries.FirstOrDefault(e => e.Text == text); if (previous is not null) { pin |= previous.Pinned; Entries.Remove(previous); } if (Entries.Count >= 100 && Entries.All(e => e.Pinned)) throw new InvalidOperationException("已固定 100 项,请先取消固定或删除一项。"); Entries.Insert(0, new(text, process, DateTime.Now, pin)); while (Entries.Count > 100) Entries.Remove(Entries.Last(e => !e.Pinned)); if (pin) try { SavePins(); } catch { Entries.Clear(); foreach (var entry in snapshot) Entries.Add(entry); throw; } Changed?.Invoke(); } public void TogglePin(ClipRecord entry) { int index = Entries.IndexOf(entry); if (index < 0) return; Entries[index] = entry with { Pinned = !entry.Pinned }; try { SavePins(); } catch { Entries[index] = entry; throw; } Changed?.Invoke(); } public void Delete(ClipRecord entry) { int index = Entries.IndexOf(entry); if (index < 0) return; Entries.RemoveAt(index); try { SavePins(); } catch { Entries.Insert(index, entry); throw; } Changed?.Invoke(); } public void ClearHistory() { foreach (var entry in Entries.Where(e => !e.Pinned).ToArray()) Entries.Remove(entry); Changed?.Invoke(); } public void SavePreferences() { Directory.CreateDirectory(root); QuickToolPaths.AtomicWrite(Path.Combine(root, "clipboard-settings.json"), Encoding.UTF8.GetBytes(JsonSerializer.Serialize(ExcludedProcesses))); } private void SavePins() { Directory.CreateDirectory(root); byte[] bytes = JsonSerializer.SerializeToUtf8Bytes(Entries.Where(e => e.Pinned).ToArray()); if (bytes.Length > 8 * 1024 * 1024 - 4096) throw new IOException("固定片段总容量超过 8 MiB,请减少片段数量或长度。"); QuickToolPaths.AtomicWrite(Path.Combine(root, "pinned-clips.bin"), ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser)); } public void Dispose() { Stop(); retry.Stop(); } [DllImport("user32.dll", SetLastError = true)] private static extern bool AddClipboardFormatListener(nint hwnd); [DllImport("user32.dll")] private static extern bool RemoveClipboardFormatListener(nint hwnd); [DllImport("user32.dll")] private static extern nint GetClipboardOwner(); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint hwnd, out uint pid); } public static class QuickToolPaths { internal static string? ValidationDataRoot; public static string Data => ValidationDataRoot ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEToolBox", "CrossVersion", "QuickTools"); public static void AtomicWrite(string path, byte[] bytes) { Directory.CreateDirectory(Path.GetDirectoryName(path)!); string temp = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { File.WriteAllBytes(temp, bytes); File.Move(temp, path, true); } finally { if (File.Exists(temp)) File.Delete(temp); } } }