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
feat: search the history by text and file names
baiyuze48df7e5f7893
diff --git a/client-core/cmd/copysyncd/main.go b/client-core/cmd/copysyncd/main.goindex be3283a..7a625b6 100644--- a/client-core/cmd/copysyncd/main.go+++ b/client-core/cmd/copysyncd/main.go@@ -342,6 +342,7 @@ func run(dataDir string) error {Fetch: engine.Fetch,FetchForPreview: engine.FetchForPreview,ApplyToClipboard: engine.ApplyToClipboard,+ SearchHistory: engine.SearchHistory,ImagePreview: engine.ImagePreview,CacheBytesUsed: blobs.Size,Permission: func() clipboard.Permission {diff --git a/client-core/internal/rpc/search_test.go b/client-core/internal/rpc/search_test.gonew file mode 100644index 0000000..dff4737--- /dev/null+++ b/client-core/internal/rpc/search_test.go@@ -0,0 +1,38 @@+package rpc++import (+ "context"+ "testing"++ "github.com/baiyuze/copysync/client-core/internal/store"+ pb "github.com/baiyuze/copysync/proto/gen/copysync/v1"+)++func TestListHistorySearch(t *testing.T) {+ var gotQuery string+ s := NewServer(Deps{SearchHistory: func(query string, limit int) ([]store.Clip, error) {+ gotQuery = query+ return []store.Clip{+ {ID: "t", Kind: store.KindText, TextPreview: "季度汇报"},+ {ID: "f", Kind: store.KindFile, Items: []store.Item{{Name: "季度汇报.key"}}},+ }, nil+ }}, NewHub(), "test-token")++ resp, err := s.ListHistory(context.Background(), &pb.ListHistoryRequest{Query: " 季度 ", Limit: 200})+ if err != nil {+ t.Fatal(err)+ }+ // 界面靠 searched 区分「搜过了」与旧版后台服务原样返回的全部记录+ if !resp.GetSearched() || len(resp.GetRecords()) != 2 || gotQuery != "季度" {+ t.Fatalf("searched=%v records=%d query=%q", resp.GetSearched(), len(resp.GetRecords()), gotQuery)+ }++ resp, err = s.ListHistory(context.Background(), &pb.ListHistoryRequest{+ Query: "季度", KindFilter: pb.ClipKind_CLIP_KIND_FILE})+ if err != nil {+ t.Fatal(err)+ }+ if len(resp.GetRecords()) != 1 || resp.GetRecords()[0].GetId() != "f" {+ t.Errorf("搜索结果没有按类型过滤:%v", resp.GetRecords())+ }+}diff --git a/client-core/internal/rpc/server.go b/client-core/internal/rpc/server.goindex 4b0a052..dcccd4b 100644--- a/client-core/internal/rpc/server.go+++ b/client-core/internal/rpc/server.go@@ -7,6 +7,7 @@ import ("errors""fmt""net"+ "strings""time""google.golang.org/grpc"@@ -44,6 +45,8 @@ type Deps struct {ImagePreview func(ctx context.Context, clipID string, index int) (path, name string, count int, err error)Permission func() clipboard.PermissionOpenPermissionSettings func() error+ // SearchHistory 按文字内容与文件名搜索复制记录,见 sync.Engine.SearchHistory+ SearchHistory func(query string, limit int) ([]store.Clip, error)// Network 返回最近一轮网络出口探测的结果Network func() *pb.NetworkInfoDevices func() (self *pb.Device, peers []*pb.Device)@@ -189,6 +192,9 @@ func (s *Server) Subscribe(req *pb.SubscribeRequest,func (s *Server) ListHistory(_ context.Context,req *pb.ListHistoryRequest) (*pb.ListHistoryResponse, error) {+ if q := strings.TrimSpace(req.GetQuery()); q != "" {+ return s.searchHistory(q, req)+ }var before time.Timeif req.GetBeforeUnix() > 0 {before = time.Unix(req.GetBeforeUnix(), 0)@@ -204,6 +210,24 @@ func (s *Server) ListHistory(_ context.Context,return &pb.ListHistoryResponse{Records: out}, nil}+func (s *Server) searchHistory(query string, req *pb.ListHistoryRequest) (*pb.ListHistoryResponse, error) {+ if s.deps.SearchHistory == nil {+ return nil, status.Error(codes.Unimplemented, "搜索未接入")+ }+ clips, err := s.deps.SearchHistory(query, int(req.GetLimit()))+ if err != nil {+ return nil, status.Errorf(codes.Internal, "搜索历史: %v", err)+ }+ out := make([]*pb.ClipRecord, 0, len(clips))+ for _, c := range clips {+ if k := req.GetKindFilter(); k != pb.ClipKind_CLIP_KIND_UNSPECIFIED && pb.ClipKind(c.Kind) != k {+ continue+ }+ out = append(out, clipToProto(c))+ }+ return &pb.ListHistoryResponse{Records: out, Searched: true}, nil+}+func (s *Server) DeleteHistory(_ context.Context, req *pb.DeleteHistoryRequest) (*pb.Empty, error) {var err errorif req.GetAll() {diff --git a/client-core/internal/store/store.go b/client-core/internal/store/store.goindex 1e9b8bf..d5f2a3d 100644--- a/client-core/internal/store/store.go+++ b/client-core/internal/store/store.go@@ -9,6 +9,7 @@ import ("encoding/json""errors""fmt"+ "strings""time""github.com/baiyuze/copysync/client-core/internal/clipfilter"@@ -296,6 +297,24 @@ func (s *Store) ListClips(limit int, before time.Time, kind Kind) ([]Clip, errorreturn s.queryClips(q, args...)}+// SearchClips 找出文字内容或文件名可能包含 query 的记录,按时间倒序,最多 limit 条。+//+// 这是粗筛:LIKE 只对 ASCII 不分大小写;没存纯文本的 HTML 记录按 HTML 源码匹配,+// 标签名也会命中。由调用方按纯文本再核对一遍(见 sync.Engine.SearchHistory)。+// 剪贴板图片的文件名是生成的(image.png),界面上也不显示,不参与匹配。+func (s *Store) SearchClips(query string, limit int) ([]Clip, error) {+ if limit <= 0 || limit > 500 {+ limit = 100+ }+ like := "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(query) + "%"+ return s.queryClips(`SELECT `+clipCols+` FROM clips+WHERE (kind = ? AND text_content LIKE ? ESCAPE '\')+ OR (kind = ? AND (text_plain LIKE ? ESCAPE '\' OR (text_plain = '' AND text_content LIKE ? ESCAPE '\')))+ OR (kind <> ? AND EXISTS (SELECT 1 FROM clip_items i WHERE i.clip_id = clips.id AND i.name LIKE ? ESCAPE '\'))+ORDER BY created_at DESC LIMIT ?`,+ KindText, like, KindHTML, like, like, KindImage, like, limit)+}+const clipCols = `id, kind, status, origin_device_id, origin_device_name, outgoing,total_size, text_preview, text_content, text_plain, cache_path,source_paths, error, created_at, expires_at`diff --git a/client-core/internal/store/store_test.go b/client-core/internal/store/store_test.goindex 541fa80..f17a8d8 100644--- a/client-core/internal/store/store_test.go+++ b/client-core/internal/store/store_test.go@@ -154,6 +154,54 @@ func TestListClipsKindFilter(t *testing.T) {}}+func TestSearchClips(t *testing.T) {+ s := openTest(t)+ now := time.Now().Truncate(time.Second)+ text := sampleClip("text", now)+ text.Kind, text.Items = KindText, nil+ text.TextContent = "Rollback plan in section 3"+ html := sampleClip("html", now.Add(time.Minute))+ html.Kind, html.Items = KindHTML, nil+ html.TextContent, html.TextPlain = `<div class="note">季度汇报</div>`, "季度汇报"+ file := sampleClip("file", now.Add(2*time.Minute)) // a.txt 与 docs+ image := sampleClip("image", now.Add(3*time.Minute))+ image.Kind, image.Items = KindImage, []Item{{Name: "image.png"}}+ percent := sampleClip("percent", now.Add(4*time.Minute))+ percent.Kind, percent.Items, percent.TextContent = KindText, nil, "灰度 10% 发布"+ for _, c := range []Clip{text, html, file, image, percent} {+ if err := s.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ ids := func(query string) []string {+ got, err := s.SearchClips(query, 10)+ if err != nil {+ t.Fatal(err)+ }+ var out []string+ for _, c := range got {+ out = append(out, c.ID)+ }+ return out+ }+ for query, want := range map[string]string{+ "ROLLBACK": "text", // 不分大小写+ "季度": "html", // HTML 按存下的纯文本匹配+ "div": "", // 有纯文本时,标签不算+ "A.TXT": "file", // 文件名+ "docs": "file", // 文件夹名+ "image": "", // 剪贴板图片生成的文件名不参与+ "10%": "percent", // % 按字面匹配,不是通配符+ "1_%": "",+ } {+ got := ids(query)+ if want == "" && len(got) != 0 || want != "" && (len(got) != 1 || got[0] != want) {+ t.Errorf("搜索 %q 得到 %v,应为 %q", query, got, want)+ }+ }+}+// GC 依赖这个查询找出该删的记录;边界判定错了会导致缓存永不释放。func TestExpiredClips(t *testing.T) {s := openTest(t)diff --git a/client-core/internal/sync/search.go b/client-core/internal/sync/search.gonew file mode 100644index 0000000..81f2509--- /dev/null+++ b/client-core/internal/sync/search.go@@ -0,0 +1,68 @@+package sync++import (+ "slices"+ "strings"+ "unicode"++ "github.com/baiyuze/copysync/client-core/internal/store"+)++// SearchHistory 搜索复制记录:文字内容或文件名包含 query 的,不分大小写,按时间倒序,最多 limit 条。+//+// 数据库只能粗筛(见 store.SearchClips),这里按用户看得到的文字再核对一遍:+// HTML 记录看纯文本,不看标签。匹配处不在预览片段里的文字记录,预览换成匹配处前后的一段,+// 列表里一眼能看出为什么搜到了它。+func (e *Engine) SearchHistory(query string, limit int) ([]store.Clip, error) {+ q := []rune(strings.Map(unicode.ToLower, strings.TrimSpace(query)))+ if len(q) == 0 {+ return nil, nil+ }+ candidates, err := e.store.SearchClips(string(q), limit)+ if err != nil {+ return nil, err+ }+ out := candidates[:0]+ for _, c := range candidates {+ if c.Kind != store.KindImage && slices.ContainsFunc(c.Items, func(it store.Item) bool {+ return indexFold(it.Name, q) >= 0+ }) {+ out = append(out, c)+ continue+ }+ if c.Kind != store.KindText && c.Kind != store.KindHTML {+ continue+ }+ text := plainText(c)+ at := indexFold(text, q)+ if at < 0 {+ continue+ }+ if indexFold(c.TextPreview, q) < 0 {+ c.TextPreview = snippet(text, at)+ }+ out = append(out, c)+ }+ return out, nil+}++// indexFold 返回 q(已转小写)在 s 里第一次出现的位置,按 rune 计,不分大小写;找不到返回 -1。+func indexFold(s string, q []rune) int {+ r := []rune(strings.Map(unicode.ToLower, s)) // 逐个 rune 转换,位置与原文一一对应+ for i := 0; i+len(q) <= len(r); i++ {+ if slices.Equal(r[i:i+len(q)], q) {+ return i+ }+ }+ return -1+}++// snippet 从匹配处往前留一小段上下文开始截取预览,前面被截掉的部分用省略号表示。+func snippet(text string, at int) string {+ const lead = 16+ r := []rune(text)+ if at <= lead {+ return preview(text)+ }+ return "…" + preview(string(r[at-lead:]))+}diff --git a/client-core/internal/sync/search_test.go b/client-core/internal/sync/search_test.gonew file mode 100644index 0000000..9f0362f--- /dev/null+++ b/client-core/internal/sync/search_test.go@@ -0,0 +1,71 @@+package sync++import (+ "strings"+ "testing"+ "time"++ "github.com/baiyuze/copysync/client-core/internal/store"+)++func TestSearchHistory(t *testing.T) {+ e := newBacklogEngine(t, &fakePeers{})+ now := time.Now().Truncate(time.Second)+ long := strings.Repeat("前面的内容很长,", 30) + "回滚预案见文档第 3 节"+ clips := []store.Clip{+ {ID: "long", Kind: store.KindText, TextContent: long, TextPreview: preview(long)},+ // 旧版本存下的 HTML 没有纯文本:只能从 HTML 里提取,标签名不算+ {ID: "legacy", Kind: store.KindHTML, TextContent: `<div class="Rollout">灰度发布</div>`,+ TextPreview: "灰度发布"},+ {ID: "file", Kind: store.KindFile, Items: []store.Item{{Name: "Contract-Signed.PDF"}},+ TextPreview: "Contract-Signed.PDF"},+ }+ for i, c := range clips {+ c.Status = store.StatusReady+ c.CreatedAt = now.Add(time.Duration(i) * time.Minute)+ c.ExpiresAt = c.CreatedAt.Add(time.Hour)+ if err := e.store.PutClip(c); err != nil {+ t.Fatal(err)+ }+ }++ find := func(query string) []store.Clip {+ got, err := e.SearchHistory(query, 50)+ if err != nil {+ t.Fatal(err)+ }+ return got+ }++ got := find("回滚预案")+ if len(got) != 1 || got[0].ID != "long" {+ t.Fatalf("长文本后半段的匹配:%v", got)+ }+ // 匹配处在原来的预览之外,预览换成它前后的一段+ if p := got[0].TextPreview; !strings.HasPrefix(p, "…") || !strings.Contains(p, "回滚预案") {+ t.Errorf("预览没有换到匹配处:%q", p)+ }++ if got := find("灰度"); len(got) != 1 || got[0].ID != "legacy" {+ t.Errorf("没存纯文本的 HTML 应按可见文字匹配:%v", got)+ }+ if got := find("rollout"); len(got) != 0 {+ t.Errorf("HTML 的属性值不应算匹配:%v", got)+ }+ if got := find(" contract-signed "); len(got) != 1 || got[0].ID != "file" {+ t.Errorf("文件名不分大小写、去掉首尾空格:%v", got)+ }+ if got := find(" "); len(got) != 0 {+ t.Errorf("空白的搜索词不应返回记录:%v", got)+ }+}++func TestIndexFold(t *testing.T) {+ q := []rune("straße")+ if i := indexFold("Die STRAßE ist lang", q); i != 4 {+ t.Errorf("indexFold = %d,应为 4(按 rune 计,不分大小写)", i)+ }+ if i := indexFold("没有", []rune("有没")); i != -1 {+ t.Errorf("找不到时应为 -1,得到 %d", i)+ }+}diff --git a/proto/copysync/v1/daemon.proto b/proto/copysync/v1/daemon.protoindex 79016d1..e1d89b0 100644--- a/proto/copysync/v1/daemon.proto+++ b/proto/copysync/v1/daemon.proto@@ -166,10 +166,16 @@ message ListHistoryRequest {int32 limit = 1;int64 before_unix = 2; // 分页游标ClipKind kind_filter = 3; // UNSPECIFIED 表示不过滤++ // 搜索词:非空时只返回文字内容或文件名包含它的记录(不分大小写),按时间倒序,+ // 忽略 before_unix。匹配处不在预览片段里的文字记录,text_preview 换成匹配处前后的一段。+ string query = 4;}message ListHistoryResponse {repeated ClipRecord records = 1;+ // 按 query 搜索过。旧版后台服务不认识 query,会照常返回全部记录,界面据此识别+ bool searched = 2;}message DeleteHistoryRequest {diff --git a/proto/gen/copysync/v1/daemon.pb.go b/proto/gen/copysync/v1/daemon.pb.goindex ec17a25..5b41f7f 100644--- a/proto/gen/copysync/v1/daemon.pb.go+++ b/proto/gen/copysync/v1/daemon.pb.go@@ -876,10 +876,13 @@ func (*Event_PermissionChanged) isEvent_Payload() {}func (*Event_StatusChanged) isEvent_Payload() {}type ListHistoryRequest struct {- state protoimpl.MessageState `protogen:"open.v1"`- Limit int32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`- BeforeUnix int64 `protobuf:"varint,2,opt,name=before_unix,json=beforeUnix,proto3" json:"before_unix,omitempty"` // 分页游标- KindFilter ClipKind `protobuf:"varint,3,opt,name=kind_filter,json=kindFilter,proto3,enum=copysync.v1.ClipKind" json:"kind_filter,omitempty"` // UNSPECIFIED 表示不过滤+ state protoimpl.MessageState `protogen:"open.v1"`+ Limit int32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"`+ BeforeUnix int64 `protobuf:"varint,2,opt,name=before_unix,json=beforeUnix,proto3" json:"before_unix,omitempty"` // 分页游标+ KindFilter ClipKind `protobuf:"varint,3,opt,name=kind_filter,json=kindFilter,proto3,enum=copysync.v1.ClipKind" json:"kind_filter,omitempty"` // UNSPECIFIED 表示不过滤+ // 搜索词:非空时只返回文字内容或文件名包含它的记录(不分大小写),按时间倒序,+ // 忽略 before_unix。匹配处不在预览片段里的文字记录,text_preview 换成匹配处前后的一段。+ Query string `protobuf:"bytes,4,opt,name=query,proto3" json:"query,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -935,9 +938,18 @@ func (x *ListHistoryRequest) GetKindFilter() ClipKind {return ClipKind_CLIP_KIND_UNSPECIFIED}+func (x *ListHistoryRequest) GetQuery() string {+ if x != nil {+ return x.Query+ }+ return ""+}+type ListHistoryResponse struct {- state protoimpl.MessageState `protogen:"open.v1"`- Records []*ClipRecord `protobuf:"bytes,1,rep,name=records,proto3" json:"records,omitempty"`+ state protoimpl.MessageState `protogen:"open.v1"`+ Records []*ClipRecord `protobuf:"bytes,1,rep,name=records,proto3" json:"records,omitempty"`+ // 按 query 搜索过。旧版后台服务不认识 query,会照常返回全部记录,界面据此识别+ Searched bool `protobuf:"varint,2,opt,name=searched,proto3" json:"searched,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -979,6 +991,13 @@ func (x *ListHistoryResponse) GetRecords() []*ClipRecord {return nil}+func (x *ListHistoryResponse) GetSearched() bool {+ if x != nil {+ return x.Searched+ }+ return false+}+type DeleteHistoryRequest struct {state protoimpl.MessageState `protogen:"open.v1"`Ids []string `protobuf:"bytes,1,rep,name=ids,proto3" json:"ids,omitempty"`@@ -2419,15 +2438,17 @@ const file_copysync_v1_daemon_proto_rawDesc = "" +"\x0edevice_changed\x18\x05 \x01(\v2\x13.copysync.v1.DeviceH\x00R\rdeviceChanged\x12Q\n" +"\x12permission_changed\x18\x06 \x01(\x0e2 .copysync.v1.ClipboardPermissionH\x00R\x11permissionChanged\x12<\n" +"\x0estatus_changed\x18\a \x01(\v2\x13.copysync.v1.StatusH\x00R\rstatusChangedB\t\n" +- "\apayload\"\x83\x01\n" ++ "\apayload\"\x99\x01\n" +"\x12ListHistoryRequest\x12\x14\n" +"\x05limit\x18\x01 \x01(\x05R\x05limit\x12\x1f\n" +"\vbefore_unix\x18\x02 \x01(\x03R\n" +"beforeUnix\x126\n" +"\vkind_filter\x18\x03 \x01(\x0e2\x15.copysync.v1.ClipKindR\n" +- "kindFilter\"H\n" ++ "kindFilter\x12\x14\n" ++ "\x05query\x18\x04 \x01(\tR\x05query\"d\n" +"\x13ListHistoryResponse\x121\n" +- "\arecords\x18\x01 \x03(\v2\x17.copysync.v1.ClipRecordR\arecords\":\n" ++ "\arecords\x18\x01 \x03(\v2\x17.copysync.v1.ClipRecordR\arecords\x12\x1a\n" ++ "\bsearched\x18\x02 \x01(\bR\bsearched\":\n" +"\x14DeleteHistoryRequest\x12\x10\n" +"\x03ids\x18\x01 \x03(\tR\x03ids\x12\x10\n" +"\x03all\x18\x02 \x01(\bR\x03all\"V\n" +diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dartindex 43ac3f0..0fef235 100644--- a/ui/lib/app_state.dart+++ b/ui/lib/app_state.dart@@ -42,6 +42,13 @@ class AppState extends ChangeNotifier {/// 正在传输的记录的进度(0–1),只在界面上展示,传完即移除。final Map<String, double> _progress = {};+ /// 复制记录的搜索:搜索词,以及后台服务返回的结果(还没出结果时为 null)。+ /// 界面只加载最新的 200 条,更早的记录只有后台服务能搜到,所以不在界面里筛选。+ String _query = '';+ List<ClipRecord>? _searchResults;+ Timer? _searchTimer;+ int _searchSeq = 0; // 只采用最后一次搜索的结果,先发出的请求可能后返回+/// 待用户核对指纹的配对请求。非空时界面弹出确认。Device? _pendingPairing;final Set<String> _handledPairingSessions = {};@@ -58,6 +65,13 @@ class AppState extends ChangeNotifier {List<Device> get peers => List.unmodifiable(_peers);List<ClipRecord> get records => List.unmodifiable(_records);+ /// 正在搜索复制记录(搜索词不是空白)。+ bool get searching => _query.trim().isNotEmpty;+ String get searchQuery => _query.trim();++ /// 搜到的记录,按时间倒序;没在搜索、或这次搜索还没出结果时为 null。+ List<ClipRecord>? get searchResults => _searchResults == null ? null : List.unmodifiable(_searchResults!);+/// 传输进度;总量未知或尚未开始时为 null。double? progressOf(String clipId) => _progress[clipId];Device? get pendingPairing => _pendingPairing;@@ -76,6 +90,7 @@ class AppState extends ChangeNotifier {@overridevoid dispose() {_retry?.cancel();+ _searchTimer?.cancel();_events?.cancel();_conn?.close();super.dispose();@@ -115,6 +130,7 @@ class AppState extends ChangeNotifier {_serviceState = null;_setLink(LinkState.online, null);_ensureServiceCurrent();+ if (searching) _scheduleSearch(Duration.zero);} on DaemonNotRunning {await _refreshServiceState();_scheduleRetry(appL10n.linkServiceNotRunning);@@ -241,12 +257,16 @@ class AppState extends ChangeNotifier {// 否则界面上会出现两行,其中「接收中」那行的进度条永远停不下来case Event_Payload.clipAdded:_upsert(ev.clipAdded);+ // 新记录该不该出现在搜索结果里,只有后台服务知道+ if (!_patchSearch(ev.clipAdded)) _scheduleSearch(const Duration(milliseconds: 300));case Event_Payload.clipUpdated:_upsert(ev.clipUpdated);+ _patchSearch(ev.clipUpdated);case Event_Payload.clipRemoved:_records.removeWhere((r) => r.id == ev.clipRemoved);+ _searchResults?.removeWhere((r) => r.id == ev.clipRemoved);case Event_Payload.deviceChanged:_onDeviceChanged(ev.deviceChanged);@@ -284,6 +304,7 @@ class AppState extends ChangeNotifier {if (r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY) {// 用户点了「拉取到本机」,开始传了_records[i] = r.deepCopy()..status = ClipStatus.CLIP_STATUS_FETCHING;+ _patchSearch(_records[i]);} else if (r.status != ClipStatus.CLIP_STATUS_FETCHING) {return; // 已经传完的记录,迟到的进度事件不能把它拉回「接收中」}@@ -403,12 +424,67 @@ class AppState extends ChangeNotifier {);if (all) {_records.clear();+ _searchResults?.clear();} else if (ids != null) {_records.removeWhere((r) => ids.contains(r.id));+ _searchResults?.removeWhere((r) => ids.contains(r.id));}notifyListeners();}+ // ─────────────────────────── 搜索复制记录 ───────────────────────────++ /// 输入搜索词。停顿一下再向后台服务查询,不必每敲一个字就查一次;空白表示不搜索。+ /// [notify] 为 false 用于页面销毁时清掉搜索:那时界面树已锁定,不能再通知重建。+ void search(String query, {bool notify = true}) {+ _query = query;+ _searchTimer?.cancel();+ if (!searching) {+ _searchSeq++;+ _searchResults = null;+ if (notify) notifyListeners();+ return;+ }+ _scheduleSearch(const Duration(milliseconds: 200));+ }++ void _scheduleSearch(Duration delay) {+ if (!searching) return;+ _searchTimer?.cancel();+ _searchTimer = Timer(delay, _runSearch);+ }++ Future<void> _runSearch() async {+ final query = searchQuery;+ final seq = ++_searchSeq;+ List<ClipRecord> found;+ try {+ final r = await requestSearch(query);+ // 旧版后台服务不认识搜索词,会原样返回全部记录:退回到只在已加载的记录里找+ found = r.searched ? List.of(r.records) : _records.where((x) => matchesSearch(x, query)).toList();+ } catch (_) {+ found = _records.where((x) => matchesSearch(x, query)).toList();+ }+ if (seq != _searchSeq || query != searchQuery) return;+ _searchResults = found;+ notifyListeners();+ }++ /// 向后台服务搜索复制记录。界面测试与截图里由子类给出演示结果。+ @protected+ Future<ListHistoryResponse> requestSearch(String query) =>+ _client.listHistory(ListHistoryRequest(limit: 200, query: query));++ /// 搜索结果里的同一条记录跟着更新状态(拉取进度、失败等),预览保留搜索给的那一段。+ /// 返回这条记录在不在结果里。+ bool _patchSearch(ClipRecord r) {+ final results = _searchResults;+ final i = results?.indexWhere((x) => x.id == r.id) ?? -1;+ if (i < 0) return false;+ results![i] = r.deepCopy()..textPreview = results[i].textPreview;+ return true;+ }+Future<void> fetch(String clipId) =>_client.fetch(FetchRequest(clipId: clipId));@@ -455,3 +531,13 @@ class AppState extends ChangeNotifier {};}}++/// 在界面已有的信息里判断一条记录是否匹配搜索词:预览片段或文件名包含它,不分大小写。+/// 只在后台服务不支持搜索时用;正常情况下由后台服务按全文搜索。+bool matchesSearch(ClipRecord r, String query) {+ final q = query.toLowerCase();+ if (r.kind != ClipKind.CLIP_KIND_IMAGE && r.items.any((i) => i.name.toLowerCase().contains(q))) return true;+ return r.kind != ClipKind.CLIP_KIND_FILE &&+ r.kind != ClipKind.CLIP_KIND_IMAGE &&+ r.textPreview.toLowerCase().contains(q);+}diff --git a/ui/lib/gen/copysync/v1/daemon.pb.dart b/ui/lib/gen/copysync/v1/daemon.pb.dartindex 58d118d..6adebfe 100644--- a/ui/lib/gen/copysync/v1/daemon.pb.dart+++ b/ui/lib/gen/copysync/v1/daemon.pb.dart@@ -831,11 +831,13 @@ class ListHistoryRequest extends $pb.GeneratedMessage {$core.int? limit,$fixnum.Int64? beforeUnix,ClipKind? kindFilter,+ $core.String? query,}) {final result = ListHistoryRequest._();if (limit != null) result.limit = limit;if (beforeUnix != null) result.beforeUnix = beforeUnix;if (kindFilter != null) result.kindFilter = kindFilter;+ if (query != null) result.query = query;return result;}@@ -856,6 +858,7 @@ class ListHistoryRequest extends $pb.GeneratedMessage {..aInt64(2, _omitFieldNames ? '' : 'beforeUnix')..aE<ClipKind>(3, _omitFieldNames ? '' : 'kindFilter',enumValues: ClipKind.values)+ ..aOS(4, _omitFieldNames ? '' : 'query')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -906,14 +909,27 @@ class ListHistoryRequest extends $pb.GeneratedMessage {$core.bool hasKindFilter() => $_has(2);@$pb.TagNumber(3)void clearKindFilter() => $_clearField(3);++ /// 搜索词:非空时只返回文字内容或文件名包含它的记录(不分大小写),按时间倒序,+ /// 忽略 before_unix。匹配处不在预览片段里的文字记录,text_preview 换成匹配处前后的一段。+ @$pb.TagNumber(4)+ $core.String get query => $_getSZ(3);+ @$pb.TagNumber(4)+ set query($core.String value) => $_setString(3, value);+ @$pb.TagNumber(4)+ $core.bool hasQuery() => $_has(3);+ @$pb.TagNumber(4)+ void clearQuery() => $_clearField(4);}class ListHistoryResponse extends $pb.GeneratedMessage {factory ListHistoryResponse({$core.Iterable<ClipRecord>? records,+ $core.bool? searched,}) {final result = ListHistoryResponse._();if (records != null) result.records.addAll(records);+ if (searched != null) result.searched = searched;return result;}@@ -932,6 +948,7 @@ class ListHistoryResponse extends $pb.GeneratedMessage {createEmptyInstance: ListHistoryResponse.$_createMessage)..pPM<ClipRecord>(1, _omitFieldNames ? '' : 'records',subBuilder: ClipRecord.$_createMessage)+ ..aOB(2, _omitFieldNames ? '' : 'searched')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -959,6 +976,16 @@ class ListHistoryResponse extends $pb.GeneratedMessage {@$pb.TagNumber(1)$pb.PbList<ClipRecord> get records => $_getList(0);++ /// 按 query 搜索过。旧版后台服务不认识 query,会照常返回全部记录,界面据此识别+ @$pb.TagNumber(2)+ $core.bool get searched => $_getBF(1);+ @$pb.TagNumber(2)+ set searched($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasSearched() => $_has(1);+ @$pb.TagNumber(2)+ void clearSearched() => $_clearField(2);}class DeleteHistoryRequest extends $pb.GeneratedMessage {diff --git a/ui/lib/gen/copysync/v1/daemon.pbjson.dart b/ui/lib/gen/copysync/v1/daemon.pbjson.dartindex 8be821f..f18c73c 100644--- a/ui/lib/gen/copysync/v1/daemon.pbjson.dart+++ b/ui/lib/gen/copysync/v1/daemon.pbjson.dart@@ -331,6 +331,7 @@ const ListHistoryRequest$json = {'6': '.copysync.v1.ClipKind','10': 'kindFilter'},+ {'1': 'query', '3': 4, '4': 1, '5': 9, '10': 'query'},],};@@ -338,7 +339,7 @@ const ListHistoryRequest$json = {final $typed_data.Uint8List listHistoryRequestDescriptor = $convert.base64Decode('ChJMaXN0SGlzdG9yeVJlcXVlc3QSFAoFbGltaXQYASABKAVSBWxpbWl0Eh8KC2JlZm9yZV91bm''l4GAIgASgDUgpiZWZvcmVVbml4EjYKC2tpbmRfZmlsdGVyGAMgASgOMhUuY29weXN5bmMudjEu'- 'Q2xpcEtpbmRSCmtpbmRGaWx0ZXI=');+ 'Q2xpcEtpbmRSCmtpbmRGaWx0ZXISFAoFcXVlcnkYBCABKAlSBXF1ZXJ5');@$core.Deprecated('Use listHistoryResponseDescriptor instead')const ListHistoryResponse$json = {@@ -352,13 +353,14 @@ const ListHistoryResponse$json = {'6': '.copysync.v1.ClipRecord','10': 'records'},+ {'1': 'searched', '3': 2, '4': 1, '5': 8, '10': 'searched'},],};/// Descriptor for `ListHistoryResponse`. Decode as a `google.protobuf.DescriptorProto`.final $typed_data.Uint8List listHistoryResponseDescriptor = $convert.base64Decode('ChNMaXN0SGlzdG9yeVJlc3BvbnNlEjEKB3JlY29yZHMYASADKAsyFy5jb3B5c3luYy52MS5DbG'- 'lwUmVjb3JkUgdyZWNvcmRz');+ 'lwUmVjb3JkUgdyZWNvcmRzEhoKCHNlYXJjaGVkGAIgASgIUghzZWFyY2hlZA==');@$core.Deprecated('Use deleteHistoryRequestDescriptor instead')const DeleteHistoryRequest$json = {diff --git a/ui/lib/icons.dart b/ui/lib/icons.dartindex 88e3104..1533a65 100644--- a/ui/lib/icons.dart+++ b/ui/lib/icons.dart@@ -21,6 +21,10 @@ abstract final class AppIcons {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 search => _pick(CupertinoIcons.search, FluentIcons.search_24_regular);+ // 搜索框里的清除按钮:实心圆里一个叉,与系统的搜索框一致+ static IconData get clearField =>+ _pick(CupertinoIcons.xmark_circle_fill, FluentIcons.dismiss_circle_20_filled);static IconData get textAlignLeft =>_pick(CupertinoIcons.text_alignleft, FluentIcons.text_align_left_24_regular);static IconData get questionCircle =>diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arbindex 142166e..5242e76 100644--- a/ui/lib/l10n/app_en.arb+++ b/ui/lib/l10n/app_en.arb@@ -203,6 +203,25 @@}}},+ "searchHint": "Search text and file names",+ "searchClear": "Clear search",+ "searchResultCount": "{count, plural, =1{1 match} other{{count} matches}}",+ "@searchResultCount": {+ "placeholders": {+ "count": {+ "type": "int"+ }+ }+ },+ "searchEmptyTitle": "No matches for “{query}”",+ "@searchEmptyTitle": {+ "placeholders": {+ "query": {+ "type": "String"+ }+ }+ },+ "searchEmptyBody": "Search looks through copied text and the names of copied files.","imagePreviewTitle": "Image preview","closePreview": "Close preview","previousImage": "Previous image",diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arbindex 9edd3af..c6ffa2c 100644--- a/ui/lib/l10n/app_ja.arb+++ b/ui/lib/l10n/app_ja.arb@@ -72,6 +72,11 @@"emptyRecord": "(空)","imageRecord": "画像","itemsSummary": "{name} ほか {others} 件",+ "searchHint": "テキストとファイル名を検索",+ "searchClear": "検索をクリア",+ "searchResultCount": "{count} 件見つかりました",+ "searchEmptyTitle": "「{query}」は見つかりません",+ "searchEmptyBody": "コピーしたテキストとファイル名から検索します。","imagePreviewTitle": "画像プレビュー","closePreview": "プレビューを閉じる","previousImage": "前の画像",diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dartindex a20cc93..28fc2ef 100644--- a/ui/lib/l10n/app_localizations.dart+++ b/ui/lib/l10n/app_localizations.dart@@ -416,6 +416,36 @@ abstract class AppLocalizations {/// **'Nothing of this kind'**String get historyEmptyFilteredTitle;+ /// No description provided for @searchHint.+ ///+ /// In en, this message translates to:+ /// **'Search text and file names'**+ String get searchHint;++ /// No description provided for @searchClear.+ ///+ /// In en, this message translates to:+ /// **'Clear search'**+ String get searchClear;++ /// No description provided for @searchResultCount.+ ///+ /// In en, this message translates to:+ /// **'{count, plural, =1{1 match} other{{count} matches}}'**+ String searchResultCount(int count);++ /// No description provided for @searchEmptyTitle.+ ///+ /// In en, this message translates to:+ /// **'No matches for “{query}”'**+ String searchEmptyTitle(String query);++ /// No description provided for @searchEmptyBody.+ ///+ /// In en, this message translates to:+ /// **'Search looks through copied text and the names of copied files.'**+ String get searchEmptyBody;+/// No description provided for @historyEmptyBody.////// In en, this message translates to:diff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dartindex a0a672e..bbd9b73 100644--- a/ui/lib/l10n/app_localizations_en.dart+++ b/ui/lib/l10n/app_localizations_en.dart@@ -243,6 +243,32 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get historyEmptyFilteredTitle => 'Nothing of this kind';+ @override+ String get searchHint => 'Search text and file names';++ @override+ String get searchClear => 'Clear search';++ @override+ String searchResultCount(int count) {+ String _temp0 = intl.Intl.pluralLogic(+ count,+ locale: localeName,+ other: '$count matches',+ one: '1 match',+ );+ return '$_temp0';+ }++ @override+ String searchEmptyTitle(String query) {+ return 'No matches for “$query”';+ }++ @override+ String get searchEmptyBody =>+ 'Search looks through copied text and the names of copied files.';+@overrideString get historyEmptyBody =>'Copy text, an image or a file on any paired device and it appears here.';diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dartindex 6372311..67c267f 100644--- a/ui/lib/l10n/app_localizations_ja.dart+++ b/ui/lib/l10n/app_localizations_ja.dart@@ -191,6 +191,25 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get historyEmptyFilteredTitle => 'この種類の履歴はありません';+ @override+ String get searchHint => 'テキストとファイル名を検索';++ @override+ String get searchClear => '検索をクリア';++ @override+ String searchResultCount(int count) {+ return '$count 件見つかりました';+ }++ @override+ String searchEmptyTitle(String query) {+ return '「$query」は見つかりません';+ }++ @override+ String get searchEmptyBody => 'コピーしたテキストとファイル名から検索します。';+@overrideString get historyEmptyBody => 'ペアリングしたどのデバイスでテキスト、画像、ファイルをコピーしても、ここに表示されます。';diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dartindex 99e8d34..d20ac63 100644--- a/ui/lib/l10n/app_localizations_zh.dart+++ b/ui/lib/l10n/app_localizations_zh.dart@@ -191,6 +191,25 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get historyEmptyFilteredTitle => '没有这一类的记录';+ @override+ String get searchHint => '搜索文字和文件名';++ @override+ String get searchClear => '清除搜索';++ @override+ String searchResultCount(int count) {+ return '找到 $count 条';+ }++ @override+ String searchEmptyTitle(String query) {+ return '没有找到「$query」';+ }++ @override+ String get searchEmptyBody => '搜索的是复制过的文字和文件名。';+@overrideString get historyEmptyBody => '在任意一台已配对的设备上复制文本、图片或文件,记录会出现在这里。';@@ -971,6 +990,25 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {@overrideString get historyEmptyFilteredTitle => '沒有這一類的記錄';+ @override+ String get searchHint => '搜尋文字和檔案名稱';++ @override+ String get searchClear => '清除搜尋';++ @override+ String searchResultCount(int count) {+ return '找到 $count 條';+ }++ @override+ String searchEmptyTitle(String query) {+ return '找不到「$query」';+ }++ @override+ String get searchEmptyBody => '搜尋範圍是複製過的文字和檔案名稱。';+@overrideString get historyEmptyBody => '在任何一部已配對的裝置上複製文字、圖片或檔案,記錄會出現在這裏。';@@ -1752,6 +1790,25 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {@overrideString get historyEmptyFilteredTitle => '沒有這一類的記錄';+ @override+ String get searchHint => '搜尋文字和檔名';++ @override+ String get searchClear => '清除搜尋';++ @override+ String searchResultCount(int count) {+ return '找到 $count 筆';+ }++ @override+ String searchEmptyTitle(String query) {+ return '找不到「$query」';+ }++ @override+ String get searchEmptyBody => '搜尋範圍是複製過的文字和檔名。';+@overrideString get historyEmptyBody => '在任何一台已配對的裝置上複製文字、圖片或檔案,記錄會出現在這裡。';diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arbindex edd7d5d..d8c3f9b 100644--- a/ui/lib/l10n/app_zh.arb+++ b/ui/lib/l10n/app_zh.arb@@ -72,6 +72,11 @@"emptyRecord": "(空)","imageRecord": "图片","itemsSummary": "{name} 等 {count} 项",+ "searchHint": "搜索文字和文件名",+ "searchClear": "清除搜索",+ "searchResultCount": "找到 {count} 条",+ "searchEmptyTitle": "没有找到「{query}」",+ "searchEmptyBody": "搜索的是复制过的文字和文件名。","imagePreviewTitle": "图片预览","closePreview": "关闭预览","previousImage": "上一张",diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arbindex ebc9e34..338ab25 100644--- a/ui/lib/l10n/app_zh_Hant_HK.arb+++ b/ui/lib/l10n/app_zh_Hant_HK.arb@@ -72,6 +72,11 @@"emptyRecord": "(空)","imageRecord": "圖片","itemsSummary": "{name} 等 {count} 項",+ "searchHint": "搜尋文字和檔案名稱",+ "searchClear": "清除搜尋",+ "searchResultCount": "找到 {count} 條",+ "searchEmptyTitle": "找不到「{query}」",+ "searchEmptyBody": "搜尋範圍是複製過的文字和檔案名稱。","imagePreviewTitle": "圖片預覽","closePreview": "關閉預覽","previousImage": "上一張",diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arbindex faf6a8d..a64259f 100644--- a/ui/lib/l10n/app_zh_Hant_TW.arb+++ b/ui/lib/l10n/app_zh_Hant_TW.arb@@ -72,6 +72,11 @@"emptyRecord": "(空)","imageRecord": "圖片","itemsSummary": "{name} 等 {count} 項",+ "searchHint": "搜尋文字和檔名",+ "searchClear": "清除搜尋",+ "searchResultCount": "找到 {count} 筆",+ "searchEmptyTitle": "找不到「{query}」",+ "searchEmptyBody": "搜尋範圍是複製過的文字和檔名。","imagePreviewTitle": "圖片預覽","closePreview": "關閉預覽","previousImage": "上一張",diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dartindex 4c3ab11..161aa3c 100644--- a/ui/lib/pages/history_page.dart+++ b/ui/lib/pages/history_page.dart@@ -1,4 +1,7 @@+import 'dart:io';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import '../app_state.dart';import '../gen/copysync/v1/daemon.pb.dart';@@ -21,6 +24,24 @@ class HistoryPage extends StatefulWidget {class _HistoryPageState extends State<HistoryPage> {_Filter _filter = _Filter.all;+ final _search = TextEditingController();+ final _searchFocus = FocusNode();+ AppState? _state;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ _state = AppScope.read(context);+ }++ @override+ void dispose() {+ // 离开这一页就不再搜索,回来看到的是完整的列表+ _state?.search('', notify: false);+ _search.dispose();+ _searchFocus.dispose();+ super.dispose();+ }bool _matches(ClipRecord r) => switch (_filter) {_Filter.all => true,@@ -34,48 +55,80 @@ class _HistoryPageState extends State<HistoryPage> {@overrideWidget build(BuildContext context) {final state = AppScope.of(context);- final records = state.records.where(_matches).toList();+ final searching = state.searching;+ // 搜索结果还没回来时为 null,这时列表先空着,不闪一下「没有找到」+ final records = (searching ? state.searchResults : state.records)?.where(_matches).toList();final ttl = state.config?.historyTtlSeconds.toInt();final l = context.l10n;final count = state.records.length;- return Column(+ final page = Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [PageHeader(title: l.navHistory,- subtitle: state.records.isEmpty- ? l.historyEmptySubtitle- : ttl == null- ? l.historyCount(count)- : l.historyCountKept(count, durationLabel(l, ttl)),+ subtitle: searching && records != null+ ? l.searchResultCount(records.length)+ : state.records.isEmpty+ ? l.historyEmptySubtitle+ : ttl == null+ ? l.historyCount(count)+ : l.historyCountKept(count, durationLabel(l, ttl)),actions: [- if (state.records.isNotEmpty) ...[- Segmented<_Filter>(- value: _filter,- segments: [- (_Filter.all, l.filterAll),- (_Filter.text, l.filterText),- (_Filter.image, l.filterImage),- (_Filter.file, l.filterFile),- ],- onChanged: (f) => setState(() => _filter = f),- ),+ // 搜索时不显示:清空的是全部记录,不只是搜到的这些,放在结果旁边容易误会+ if (state.records.isNotEmpty && !searching)IconAction(icon: AppIcons.trash,tooltip: l.historyClearTooltip,onTap: () => _confirmClear(context, state),),- ],],),+ // 找记录的两个办法放在一起:搜索框占满剩下的宽度,类型筛选在右边。+ // 不放进标题栏:最小窗口下标题栏放不下搜索框+ if (state.records.isNotEmpty || searching)+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.md),+ child: Row(+ children: [+ Expanded(+ child: SearchField(+ controller: _search,+ focusNode: _searchFocus,+ hint: l.searchHint,+ clearTooltip: l.searchClear,+ onChanged: state.search,+ ),+ ),+ const SizedBox(width: Insets.md),+ Segmented<_Filter>(+ value: _filter,+ segments: [+ (_Filter.all, l.filterAll),+ (_Filter.text, l.filterText),+ (_Filter.image, l.filterImage),+ (_Filter.file, l.filterFile),+ ],+ onChanged: (f) => setState(() => _filter = f),+ ),+ ],+ ),+ ),if (_needsPermission(state.status?.clipboardPermission))Padding(padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.md),child: _PermissionNotice(permission: state.status!.clipboardPermission),),Expanded(- child: records.isEmpty+ child: records == null+ ? const SizedBox.shrink()+ : records.isEmpty && searching+ ? EmptyState(+ icon: AppIcons.search,+ title: l.searchEmptyTitle(state.searchQuery),+ description: l.searchEmptyBody,+ )+ : records.isEmpty? EmptyState(icon: _filter == _Filter.all? AppIcons.docOnClipboard@@ -100,7 +153,8 @@ class _HistoryPageState extends State<HistoryPage> {sliver: SliverList.separated(itemCount: records.length,separatorBuilder: (_, _) => const Divider(indent: 44, endIndent: 8),- itemBuilder: (_, i) => _RecordRow(record: records[i]),+ itemBuilder: (_, i) =>+ _RecordRow(record: records[i], highlight: searching ? state.searchQuery : null),),),),@@ -110,6 +164,15 @@ class _HistoryPageState extends State<HistoryPage> {),],);++ // ⌘F(Windows、Linux 上是 Ctrl+F)跳到搜索框+ return CallbackShortcuts(+ bindings: {+ SingleActivator(LogicalKeyboardKey.keyF, meta: Platform.isMacOS, control: !Platform.isMacOS):+ _searchFocus.requestFocus,+ },+ child: Focus(autofocus: true, child: page),+ );}static bool _needsPermission(ClipboardPermission? p) =>@@ -172,10 +235,13 @@ class _PermissionNotice extends StatelessWidget {}class _RecordRow extends StatefulWidget {- const _RecordRow({required this.record});+ const _RecordRow({required this.record, this.highlight});final ClipRecord record;+ /// 搜索词:标题里匹配的部分标出来+ final String? highlight;+@overrideState<_RecordRow> createState() => _RecordRowState();}@@ -214,8 +280,14 @@ class _RecordRowState extends State<_RecordRow> {crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,children: [- Text(- recordTitle(r),+ Text.rich(+ TextSpan(+ children: highlightMatches(+ recordTitle(r, query: widget.highlight),+ widget.highlight,+ TextStyle(backgroundColor: p.accent.withValues(alpha: 0.28)),+ ),+ ),style: context.text.labelLarge,maxLines: 1,overflow: TextOverflow.ellipsis,@@ -331,7 +403,9 @@ IconData kindIcon(ClipRecord r) => switch (r.kind) {_ => AppIcons.questionCircle,};-String recordTitle(ClipRecord r) {+/// 记录在列表里的标题。搜索时传入 [query]:一次复制了多个文件、搜到的又不是第一个时,+/// 标题改用搜到的那个文件名打头,看得出为什么搜到了它。+String recordTitle(ClipRecord r, {String? query}) {// 图片和文件的标题按当前界面语言拼:后台服务存下的摘要是写入时的中文,不会跟着换语言if (r.kind == ClipKind.CLIP_KIND_IMAGE) return appL10n.imageRecord;if (r.kind != ClipKind.CLIP_KIND_FILE && r.textPreview.isNotEmpty) {@@ -339,5 +413,24 @@ String recordTitle(ClipRecord r) {}if (r.items.isEmpty) return appL10n.emptyRecord;if (r.items.length == 1) return r.items.first.name;- return appL10n.itemsSummary(r.items.first.name, r.items.length - 1, r.items.length);+ final q = query?.toLowerCase();+ final lead = q == null ? null : r.items.where((i) => i.name.toLowerCase().contains(q)).firstOrNull;+ return appL10n.itemsSummary((lead ?? r.items.first).name, r.items.length - 1, r.items.length);+}++/// 把 [text] 里所有不分大小写匹配 [query] 的片段套上 [mark] 样式。+/// 转小写后长度变了的少数字符(如土耳其语的 İ)对不上位置,这时不标。+List<TextSpan> highlightMatches(String text, String? query, TextStyle mark) {+ final lower = text.toLowerCase();+ final q = query?.toLowerCase() ?? '';+ if (q.isEmpty || lower.length != text.length) return [TextSpan(text: text)];+ final spans = <TextSpan>[];+ var start = 0;+ for (var i = lower.indexOf(q); i >= 0; i = lower.indexOf(q, start)) {+ if (i > start) spans.add(TextSpan(text: text.substring(start, i)));+ spans.add(TextSpan(text: text.substring(i, i + q.length), style: mark));+ start = i + q.length;+ }+ if (start < text.length) spans.add(TextSpan(text: text.substring(start)));+ return spans;}diff --git a/ui/lib/widgets/common.dart b/ui/lib/widgets/common.dartindex 8e23602..e8c81c2 100644--- a/ui/lib/widgets/common.dart+++ b/ui/lib/widgets/common.dart@@ -1,4 +1,5 @@import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import '../theme.dart';import '../i18n.dart';@@ -219,6 +220,90 @@ class Segmented<T> extends StatelessWidget {}}+/// 搜索框,对应 macOS 的 NSSearchField:浅灰底、左边放大镜,输入后右边出现清除按钮。+/// 按 Esc 时有字就清空,没字就交出焦点。不给 [width] 时占满父级给的宽度。+/// 高度定为 28,与旁边的 [Segmented] 一样高;不跟着字体变,否则换个系统字体就高低不齐。+class SearchField extends StatelessWidget {+ const SearchField({+ super.key,+ required this.controller,+ required this.hint,+ required this.clearTooltip,+ required this.onChanged,+ this.focusNode,+ this.width,+ });++ final TextEditingController controller;+ final String hint;+ final String clearTooltip;+ final ValueChanged<String> onChanged;+ final FocusNode? focusNode;+ final double? width;++ void _clear() {+ controller.clear();+ onChanged('');+ }++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final round = OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.sm),+ borderSide: BorderSide.none,+ );+ return SizedBox(+ width: width,+ height: 28,+ child: CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape): () {+ if (controller.text.isNotEmpty) {+ _clear();+ } else {+ focusNode?.unfocus();+ }+ },+ },+ child: ListenableBuilder(+ listenable: controller,+ builder: (context, _) => TextField(+ controller: controller,+ focusNode: focusNode,+ onChanged: onChanged,+ style: context.text.bodyMedium,+ expands: true,+ maxLines: null,+ textAlignVertical: TextAlignVertical.center,+ decoration: InputDecoration(+ hintText: hint,+ fillColor: p.fill,+ contentPadding: EdgeInsets.zero,+ border: round,+ enabledBorder: round,+ focusedBorder: round.copyWith(borderSide: BorderSide(color: p.accent, width: 1.5)),+ prefixIcon: Icon(AppIcons.search, size: 14, color: p.textFaint),+ prefixIconConstraints: const BoxConstraints(minWidth: 28, minHeight: 0),+ suffixIcon: controller.text.isEmpty+ ? null+ : IconButton(+ onPressed: _clear,+ tooltip: clearTooltip,+ icon: Icon(AppIcons.clearField, size: 14, color: p.textFaint),+ padding: EdgeInsets.zero,+ constraints: const BoxConstraints(minWidth: 28, minHeight: 0),+ style: const ButtonStyle(tapTargetSize: MaterialTapTargetSize.shrinkWrap),+ ),+ suffixIconConstraints: const BoxConstraints(minWidth: 28, minHeight: 0),+ ),+ ),+ ),+ ),+ );+ }+}+/// 空状态。给出下一步该做什么,而不是只说"暂无数据"。class EmptyState extends StatelessWidget {const EmptyState({diff --git a/ui/test/history_search_test.dart b/ui/test/history_search_test.dartnew file mode 100644index 0000000..c6faf31--- /dev/null+++ b/ui/test/history_search_test.dart@@ -0,0 +1,138 @@+import 'dart:io';++import 'package:fixnum/fixnum.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';++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/pages/history_page.dart';++/// 不连后台服务:搜索请求记下来,按测试给的规则回答。+class _SearchState extends AppState {+ _SearchState(this.respond);++ final ListHistoryResponse Function(String query) respond;+ final queries = <String>[];++ @override+ Future<ListHistoryResponse> requestSearch(String query) async {+ queries.add(query);+ return respond(query);+ }+}++final _report = ClipRecord(+ id: 'report',+ kind: ClipKind.CLIP_KIND_FILE,+ originDeviceName: 'MacBook Air',+ items: [ClipItem(name: 'notes.txt'), ClipItem(name: 'Quarterly report.key')],+ totalSize: Int64(2048),+);+final _note = ClipRecord(id: 'note', kind: ClipKind.CLIP_KIND_TEXT, textPreview: 'Lunch at noon', outgoing: true);++_SearchState _seed(ListHistoryResponse Function(String) respond) => _SearchState(respond)+ ..debugSeed(+ status: Status(signalingConnected: true, version: '1.7.0'),+ config: Config(language: 'en', historyTtlSeconds: Int64(3 * 86400)),+ self: Device(id: 'self', name: 'MacBook Pro'),+ records: [_note, _report],+ );++Future<void> _type(WidgetTester tester, String text) async {+ await tester.enterText(find.byType(TextField), text);+ await tester.pump(const Duration(milliseconds: 250)); // 过了停顿时间才查询+ await tester.pump();+}++void main() {+ testWidgets('停顿后才向后台服务查询,显示它返回的结果并标出匹配处', (tester) async {+ final state = _seed((q) => ListHistoryResponse(records: [_report], searched: true));+ await tester.pumpWidget(CopySyncApp(state: state));++ await tester.enterText(find.byType(TextField), 'quar');+ await tester.pump(const Duration(milliseconds: 100));+ await tester.enterText(find.byType(TextField), 'quarterly');+ await tester.pump(const Duration(milliseconds: 100));+ expect(state.queries, isEmpty);+ await tester.pump(const Duration(milliseconds: 150));+ await tester.pump();+ expect(state.queries, ['quarterly']);++ // 搜到的不是第一个文件时,标题用搜到的那个打头+ expect(find.text('Quarterly report.key and 1 more', findRichText: true), findsOneWidget);+ expect(find.text('Lunch at noon', findRichText: true), findsNothing);+ expect(find.text('1 match'), findsOneWidget);+ final title = tester.widget<RichText>(find.text('Quarterly report.key and 1 more', findRichText: true));+ final marked = <String>[];+ title.text.visitChildren((span) {+ if (span is TextSpan && span.style?.backgroundColor != null) marked.add(span.text!);+ return true;+ });+ expect(marked, ['Quarterly']);+ // 搜索时不放「清空记录」,免得以为只清空搜到的这些+ expect(find.byTooltip('Clear history'), findsNothing);+ });++ testWidgets('没有结果时说明搜的是什么,清空搜索词后回到完整列表', (tester) async {+ final state = _seed((q) => ListHistoryResponse(searched: true));+ await tester.pumpWidget(CopySyncApp(state: state));++ await _type(tester, 'zebra');+ expect(find.text('No matches for “zebra”'), findsOneWidget);+ expect(find.text('Search looks through copied text and the names of copied files.'), findsOneWidget);++ await tester.tap(find.byTooltip('Clear search'));+ await tester.pump();+ expect(find.text('Lunch at noon', findRichText: true), findsOneWidget);+ expect(find.byTooltip('Clear history'), findsOneWidget);+ });++ testWidgets('旧版后台服务不认识搜索词时,退回到在已加载的记录里找', (tester) async {+ // 旧版照常返回全部记录,没有 searched+ final state = _seed((q) => ListHistoryResponse(records: [_note, _report]));+ await tester.pumpWidget(CopySyncApp(state: state));++ await _type(tester, 'LUNCH');+ expect(find.text('Lunch at noon', findRichText: true), findsOneWidget);+ expect(find.text('notes.txt and 1 more', findRichText: true), findsNothing);+ });++ testWidgets('快捷键跳到搜索框,Esc 清空搜索词', (tester) async {+ final state = _seed((q) => ListHistoryResponse(records: [_note], searched: true));+ await tester.pumpWidget(CopySyncApp(state: state));+ await tester.pump();++ final modifier = Platform.isMacOS ? LogicalKeyboardKey.metaLeft : LogicalKeyboardKey.controlLeft;+ await tester.sendKeyDownEvent(modifier);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyF);+ await tester.sendKeyUpEvent(modifier);+ await tester.pump();+ final field = tester.widget<TextField>(find.byType(TextField));+ expect(field.focusNode!.hasFocus, isTrue);++ await _type(tester, 'lunch');+ expect(state.searching, isTrue);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(state.searching, isFalse);+ expect(field.controller!.text, isEmpty);+ });++ test('标出所有匹配处,不分大小写', () {+ const mark = TextStyle(backgroundColor: Color(0xFF000000));+ final spans = highlightMatches('Copy, copy, COPY', 'copy', mark);+ expect(spans.where((s) => s.style == mark).map((s) => s.text), ['Copy', 'copy', 'COPY']);+ expect(spans.map((s) => s.text).join(), 'Copy, copy, COPY');+ expect(highlightMatches('abc', '', mark).single.text, 'abc');+ });++ test('界面里的匹配:预览片段与文件名,剪贴板图片的文件名不算', () {+ expect(matchesSearch(_note, 'NOON'), isTrue);+ expect(matchesSearch(_report, 'quarterly'), isTrue);+ expect(matchesSearch(ClipRecord(kind: ClipKind.CLIP_KIND_IMAGE, items: [ClipItem(name: 'image.png')]), 'image'),+ isFalse);+ });+}diff --git a/ui/tool/l10n/strings.py b/ui/tool/l10n/strings.pyindex 7405053..25c9279 100644--- a/ui/tool/l10n/strings.py+++ b/ui/tool/l10n/strings.py@@ -97,6 +97,13 @@ S = [("imageRecord", "Image", "图片", "画像", "圖片", "圖片"),("itemsSummary", "{name} and {others, plural, =1{1 more} other{{others} more}}", "{name} 等 {count} 项", "{name} ほか {others} 件", "{name} 等 {count} 項", "{name} 等 {count} 項"),+ # ── 搜索复制记录 ──+ ("searchHint", "Search text and file names", "搜索文字和文件名", "テキストとファイル名を検索", "搜尋文字和檔名", "搜尋文字和檔案名稱"),+ ("searchClear", "Clear search", "清除搜索", "検索をクリア", "清除搜尋", "清除搜尋"),+ ("searchResultCount", "{count, plural, =1{1 match} other{{count} matches}}", "找到 {count} 条", "{count} 件見つかりました", "找到 {count} 筆", "找到 {count} 條"),+ ("searchEmptyTitle", "No matches for “{query}”", "没有找到「{query}」", "「{query}」は見つかりません", "找不到「{query}」", "找不到「{query}」"),+ ("searchEmptyBody", "Search looks through copied text and the names of copied files.", "搜索的是复制过的文字和文件名。", "コピーしたテキストとファイル名から検索します。", "搜尋範圍是複製過的文字和檔名。", "搜尋範圍是複製過的文字和檔案名稱。"),+# ── 图片预览 ──("imagePreviewTitle", "Image preview", "图片预览", "画像プレビュー", "圖片預覽", "圖片預覽"),("closePreview", "Close preview", "关闭预览", "プレビューを閉じる", "關閉預覽", "關閉預覽"),diff --git a/ui/tool/screenshots/screenshots_test.dart b/ui/tool/screenshots/screenshots_test.dartindex 585547e..a30d5d1 100644--- a/ui/tool/screenshots/screenshots_test.dart+++ b/ui/tool/screenshots/screenshots_test.dart@@ -39,11 +39,15 @@ final _cjk = switch (_lang) {_ => const ['PingFang'],};-/// 生成配对码、搜索附近设备都不走后台服务,直接给固定的演示数据。+/// 生成配对码、搜索附近设备、搜索复制记录都不走后台服务,直接给固定的演示数据。class _DemoState extends AppState {@overrideFuture<PairingCode> createPairingCode() async => (code: 'K7MP2X', addresses: ['192.168.1.20']);+ @override+ Future<ListHistoryResponse> requestSearch(String query) async =>+ ListHistoryResponse(records: records.where((r) => matchesSearch(r, query)), searched: true);+// 不关闭的流:后台服务那边的订阅一直开着,结束就表示后台服务断开了@overrideStream<List<NearbyDevice>> watchNearby() => (StreamController<List<NearbyDevice>>()@@ -302,6 +306,15 @@ void main() {});});+ // 搜索 release:命令行与链接两条都含有它,看得到多条结果和标出的匹配处+ testWidgets('history-search', (tester) async {+ await _shoot(tester, 'history-search', state: _demo(), settle: false, arrange: () async {+ await tester.enterText(find.byType(TextField), 'release');+ await tester.pump(const Duration(milliseconds: 300));+ await tester.pump();+ });+ });+testWidgets('history-dark', (tester) async {await _shoot(tester, 'history-dark',state: _demo(), brightness: Brightness.dark, settle: false);