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(ui): add the phone web transfer panel and the Android client
baiyuzef61b768d21ea
diff --git a/client-core/mobile/clipboard.go b/client-core/mobile/clipboard.gonew file mode 100644index 0000000..6b15d67--- /dev/null+++ b/client-core/mobile/clipboard.go@@ -0,0 +1,70 @@+package mobile++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ gosync "sync"++ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+)++// hostClipboard 是 Android 上的剪贴板:只写不读(design/phone-sync.md 3.3.2 节第 4 条)。+//+// Android 10 起后台读不到别的 App 复制的内容,所以 Read 返回 ErrUnsupported,手机发出的文字走 SubmitText。+// Peek 的变化计数只在本机写入时增加,Watcher 把这些变化认作「本机刚写的」,不会当成新复制再发出去。+type hostClipboard struct {+ host Host+ dir string // 剪贴板图片落盘的位置,宿主据此生成 content:// 地址+ mu gosync.Mutex+ count int64+}++func newHostClipboard(h Host, dir string) *hostClipboard { return &hostClipboard{host: h, dir: dir} }++func (c *hostClipboard) Peek() (clipboard.Snapshot, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ return clipboard.Snapshot{ChangeCount: c.count}, nil+}++func (c *hostClipboard) Read() (clipboard.Content, error) {+ return clipboard.Content{}, clipboard.ErrUnsupported+}++func (c *hostClipboard) Write(content clipboard.Content) error {+ var err error+ switch content.Kind {+ case clipboard.KindText:+ err = c.host.WriteClipboard("text", content.Text, "", "")+ case clipboard.KindHTML:+ err = c.host.WriteClipboard("html", content.Text, content.HTML, "")+ case clipboard.KindImage:+ // 剪贴板图片是内存里的 PNG:先落盘,宿主才能给出 content:// 地址。每次覆盖同一个文件+ if err = os.MkdirAll(c.dir, 0o700); err == nil {+ path := filepath.Join(c.dir, "image.png")+ if err = os.WriteFile(path, content.Image, 0o600); err == nil {+ err = c.host.WriteClipboard("image", "", "", path)+ }+ }+ case clipboard.KindFile:+ if len(content.Files) == 0 {+ return errors.New("没有文件")+ }+ err = c.host.WriteClipboard("files", "", "", strings.Join(content.Files, "\n"))+ default:+ return clipboard.ErrUnsupported+ }+ if err != nil {+ return err+ }+ c.mu.Lock()+ c.count+++ c.mu.Unlock()+ return nil+}++func (c *hostClipboard) Permission() clipboard.Permission { return clipboard.PermissionNotApplicable }++func (c *hostClipboard) OpenPermissionSettings() error { return nil }diff --git a/client-core/mobile/mobile.go b/client-core/mobile/mobile.gonew file mode 100644index 0000000..aad5508--- /dev/null+++ b/client-core/mobile/mobile.go@@ -0,0 +1,448 @@+// Package mobile 是 Android App 内嵌的 Go 核心(design/phone-sync.md 3.3.1、3.3.2 节),+// 用 gomobile bind 导出给 Kotlin:+//+// gomobile bind -target=android/arm64 -androidapi 29 -ldflags=-checklinkname=0 ./mobile(见 scripts/build-android.sh)+//+// 组装方式与桌面的 cmd/pasteferryd 相同,只是:+// - 只开局域网通道(服务模式固定为 lan),不连服务器;+// - 没有托盘、桌面通知、快捷粘贴、隔空传送、好友、自动更新;+// - 剪贴板只写不读:写由 Kotlin 宿主完成(Host.WriteClipboard),后台读不到别的 App 复制的内容,+// 手机发出的文字走 SubmitText RPC;+// - 对端推送来的图片和文件收完后不写剪贴板,用户点了「复制」才写。+//+// Flutter 界面与桌面一样,经本机 gRPC(127.0.0.1 随机端口 + 一次性 token)连进来:+// 端口与 token 写在数据目录的 daemon.json 里,数据目录是 App 的私有目录,别的 App 读不到。+package mobile++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "slices"+ "strings"+ gosync "sync"+ "time"++ "google.golang.org/grpc"++ "github.com/baiyuze/pasteferry/client-core/internal/cache"+ "github.com/baiyuze/pasteferry/client-core/internal/clipboard"+ "github.com/baiyuze/pasteferry/client-core/internal/config"+ "github.com/baiyuze/pasteferry/client-core/internal/gc"+ "github.com/baiyuze/pasteferry/client-core/internal/identity"+ "github.com/baiyuze/pasteferry/client-core/internal/peers"+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"+ "github.com/baiyuze/pasteferry/client-core/internal/store"+ syncengine "github.com/baiyuze/pasteferry/client-core/internal/sync"+ "github.com/baiyuze/pasteferry/client-core/internal/transport/p2p"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++// Host 由 Kotlin 宿主实现。gomobile 只支持基本类型,多个路径、设备名用换行分隔。+type Host interface {+ // WriteClipboard 把内容写进系统剪贴板。kind 是 text、html、image 或 files;+ // image 与 files 时 paths 是换行分隔的本地路径(都在数据目录里),宿主转成 FileProvider 的 content:// 地址。+ // Android 写剪贴板不需要焦点,App 在后台也能写+ WriteClipboard(kind, text, html, paths string) error+ // StatusChanged 在在线的电脑变化、或收到新内容时调用,宿主据此更新常驻通知。+ // online 是换行分隔的在线设备名;lastFrom、lastKind 是最近收到的一条的来源与类型(text、image、file),没有时为空+ StatusChanged(online, lastFrom, lastKind string)+}++var (+ mu gosync.Mutex+ running *core+)++// Start 启动核心。dataDir 是 App 私有目录下的数据目录,deviceName 是第一次运行时的设备名,+// version 是 App 的版本号。已在运行时什么也不做。+func Start(dataDir, deviceName, version string, host Host) error {+ mu.Lock()+ defer mu.Unlock()+ if running != nil {+ return nil+ }+ if host == nil {+ return errors.New("host 不能为空")+ }+ c, err := start(dataDir, deviceName, version, host)+ if err != nil {+ return err+ }+ running = c+ return nil+}++// Stop 停止核心,可以再次 Start。+func Stop() {+ mu.Lock()+ c := running+ running = nil+ mu.Unlock()+ if c != nil {+ c.stop()+ }+}++// Running 报告核心是否在运行。+func Running() bool {+ mu.Lock()+ defer mu.Unlock()+ return running != nil+}++type core struct {+ cancel context.CancelFunc+ grpc *grpc.Server+ closes []func()+ paths config.Paths+}++func (c *core) stop() {+ c.cancel()+ if c.grpc != nil {+ done := make(chan struct{})+ go func() { c.grpc.GracefulStop(); close(done) }()+ select {+ case <-done:+ case <-time.After(2 * time.Second):+ c.grpc.Stop()+ }+ }+ for i := len(c.closes) - 1; i >= 0; i-- {+ c.closes[i]()+ }+ rpc.RemoveEndpoint(c.paths.Endpoint)+}++func start(dataDir, deviceName, version string, host Host) (_ *core, err error) {+ ctx, cancel := context.WithCancel(context.Background())+ c := &core{cancel: cancel, paths: config.PathsUnder(dataDir)}+ defer func() {+ if err != nil {+ c.stop()+ }+ }()+ paths := c.paths+ if err := paths.EnsureDirs(); err != nil {+ return nil, err+ }+ cfg, err := config.Load(paths)+ if err != nil {+ return nil, err+ }+ id, err := identity.LoadOrCreate(filepath.Join(paths.Root, "identity.json"))+ if err != nil {+ return nil, err+ }+ // 一期只在局域网里用;对端推送来的图片和文件不自动写剪贴板+ before := cfg+ cfg.DeviceID = id.DeviceID+ cfg.ServiceMode = "lan"+ cfg.MediaAutoApplyDisabled = true+ if cfg.DeviceName == "" || cfg.DeviceName == config.Default().DeviceName {+ cfg.DeviceName = strings.TrimSpace(deviceName)+ }+ if !slices.Equal(before.SyncDisabledPeers, cfg.SyncDisabledPeers) || before.DeviceID != cfg.DeviceID ||+ before.ServiceMode != cfg.ServiceMode || before.MediaAutoApplyDisabled != cfg.MediaAutoApplyDisabled ||+ before.DeviceName != cfg.DeviceName {+ if err := config.Save(paths, cfg); err != nil {+ return nil, err+ }+ }+ slog.Info("隔空贴核心启动", "device_id", id.DeviceID, "name", cfg.DeviceName, "fingerprint", id.Fingerprint(), "version", version)++ db, err := store.Open(paths.DB)+ if err != nil {+ return nil, err+ }+ c.closes = append(c.closes, func() { db.Close() })+ if err := db.RecoverReceives(); err != nil {+ return nil, err+ }+ blobs, err := cache.New(paths.Cache)+ if err != nil {+ return nil, err+ }+ _ = blobs.CleanTemp()+ favorites, err := cache.New(paths.Favorites)+ if err != nil {+ return nil, err+ }++ var cfgMu gosync.RWMutex+ loadCfg := func() config.Config {+ cfgMu.RLock()+ defer cfgMu.RUnlock()+ return cfg+ }+ saveCfg := func(next config.Config) error {+ cfgMu.Lock()+ defer cfgMu.Unlock()+ next.ServiceMode = "lan" // 一期界面上没有服务器设置,防止被意外改掉+ if err := config.Save(paths, next); err != nil {+ return err+ }+ cfg = next+ return nil+ }++ hub := rpc.NewHub()++ // 剪贴板:Watcher 要一个主循环来串行执行读写;Android 上 Kotlin 自己切到主线程,这里普通 goroutine 即可+ loop := clipboard.NewMainLoop()+ go loop.Run(ctx)+ watcher := clipboard.NewWatcher(clipboard.WatcherOptions{+ Clipboard: newHostClipboard(host, filepath.Join(paths.Root, "clipboard")),+ MainLoop: loop,+ })++ var engine *syncengine.Engine+ var peerMgr *peers.Manager+ notify := newStatusNotifier(host)++ statusDirty := make(chan struct{}, 1)+ markDirty := func() {+ select {+ case statusDirty <- struct{}{}:+ default:+ }+ }++ peerMgr, err = peers.NewManager(peers.Options{+ Identity: id,+ Store: db,+ LoadConfig: loadCfg,+ StatePath: filepath.Join(paths.Root, "egress.json"),+ AppVersion: version,+ OnDeviceChanged: func(d *pb.Device) {+ hub.Publish(rpc.EventDeviceChanged(d))+ if peerMgr != nil {+ notify.online(peerMgr)+ }+ },+ OnStatusChanged: markDirty,+ OnPeerMessage: func(deviceID string, msg *pb.PeerMessage) {+ if engine != nil {+ engine.HandlePeerMessage(ctx, deviceID, msg)+ }+ },+ OnPeerStream: func(deviceID, label string, stream *p2p.Stream) {+ if engine != nil {+ engine.HandlePeerStream(deviceID, label, stream)+ } else {+ stream.Close()+ }+ },+ OnPeerReady: func(deviceID string) {+ if engine != nil {+ go engine.PeerReady(ctx, deviceID)+ }+ },+ // 一期没有好友与隔空传送:名片只带设备名,别人开来的隔空传送数据流一律关掉+ Card: func() *pb.FriendCard {+ n := loadCfg().DeviceName+ return &pb.FriendCard{DisplayName: n, DeviceName: n, Platform: "android"}+ },+ Avatar: func() []byte { return nil },+ SaveAvatar: func(string, []byte) (string, error) { return "", errors.New("不支持好友") },+ ShareableStream: func(string) bool { return false },+ InUse: func(string) bool { return false },+ })+ if err != nil {+ return nil, err+ }++ engine = syncengine.New(syncengine.Options{+ Store: db,+ Cache: blobs,+ Favorites: favorites,+ Watcher: watcher,+ DeviceID: id.DeviceID,+ DeviceName: func() string { return loadCfg().DeviceName },+ LoadConfig: loadCfg,+ Send: peerMgr.P2P().Send,+ OpenStream: peerMgr.P2P().OpenStream,+ PairedPeers: func() []string {+ _, list := peerMgr.Devices()+ ids := make([]string, 0, len(list))+ for _, d := range list {+ ids = append(ids, d.GetId())+ }+ return ids+ },+ OnClipboardResult: func(result *pb.ClipboardWriteResult) {+ hub.Publish(&pb.Event{Payload: &pb.Event_ClipboardWritten{ClipboardWritten: result}})+ },+ OnRecord: func(r *pb.ClipRecord) {+ hub.Publish(rpc.EventClipAdded(r))+ if !r.GetOutgoing() && !r.GetFavorite() {+ notify.received(r)+ }+ },+ OnRemoved: func(id string) { hub.Publish(rpc.EventClipRemoved(id)) },+ OnProgress: func(p *pb.TransferProgress) {+ hub.Publish(rpc.EventProgress(p))+ },+ })+ c.closes = append(c.closes, engine.Close)+ // 后台读不到别的 App 复制的内容,Watcher 只会看到自己写入的变化;照样接上,行为与桌面一致+ watcher.SetOnChange(func(snap clipboard.Snapshot) { go engine.HandleClipboardChange(ctx, snap) })++ // 停止时要等 Run 退出(它在退出前关掉局域网通道、放掉 8788 端口),再关 P2P:+ // 桌面上进程退出时这些自然就没了,这里要能停了再启动+ runDone := make(chan struct{})+ go func() { peerMgr.Run(ctx); close(runDone) }()+ c.closes = append(c.closes, func() {+ select {+ case <-runDone:+ case <-time.After(3 * time.Second):+ slog.Warn("等局域网通道停下超时")+ }+ peerMgr.P2P().Close()+ })+ go watcher.Run(ctx)+ go gc.New(gc.Options{+ Store: db, Cache: blobs, Favorites: favorites, LoadConfig: loadCfg,+ OnRemoved: func(ids []string) {+ for _, cid := range ids {+ hub.Publish(rpc.EventClipRemoved(cid))+ }+ },+ }).Run(ctx)++ saveCfgAndApply := func(next config.Config) error {+ prev := loadCfg()+ if err := saveCfg(next); err != nil {+ return err+ }+ if next.RealtimeSyncDisabled != prev.RealtimeSyncDisabled || next.SyncBacklog != prev.SyncBacklog ||+ !slices.Equal(next.SyncDisabledPeers, prev.SyncDisabledPeers) {+ engine.ApplySyncPolicy()+ }+ if next.LANDisabled != prev.LANDisabled {+ peerMgr.SetLANEnabled(!next.LANDisabled)+ }+ hub.Publish(rpc.EventConfigChanged(rpc.ConfigToProto(loadCfg())))+ markDirty()+ return nil+ }++ token, err := rpc.NewToken()+ if err != nil {+ return nil, err+ }+ srv := rpc.NewServer(rpc.Deps{+ Store: db,+ Paths: paths,+ Version: version,+ DeviceID: id.DeviceID,+ LoadConfig: loadCfg,+ SaveConfig: saveCfgAndApply,+ Devices: peerMgr.Devices,+ CreatePairingCode: peerMgr.CreatePairingCode,+ RedeemPairingCode: peerMgr.RedeemPairingCode,+ ConfirmPairing: peerMgr.ConfirmPairing,+ Unpair: peerMgr.Unpair,+ Reconnect: peerMgr.Reconnect,+ SetDeviceAddress: peerMgr.SetDeviceAddress,+ ShowNearby: peerMgr.ShowNearby,+ Nearby: peerMgr.Nearby,+ PairNearby: peerMgr.PairNearby,+ SignalingConnected: peerMgr.Connected,+ ServerConfigured: peerMgr.ServerConfigured,+ LANEnabled: peerMgr.LANEnabled,+ LANBlocked: peerMgr.LANBlocked,+ Fetch: engine.Fetch,+ FetchForPreview: engine.FetchForPreview,+ ApplyToClipboard: engine.ApplyToClipboardAs,+ SearchHistory: engine.SearchHistory,+ SetFavorite: engine.SetFavorite,+ SetAlias: engine.SetAlias,+ ClipDetail: engine.ClipDetail,+ ImagePreview: engine.ImagePreview,+ CacheBytesUsed: blobs.Size,+ Permission: func() clipboard.Permission { return clipboard.PermissionNotApplicable },+ Network: func() *pb.NetworkInfo {+ return &pb.NetworkInfo{Lan: peerMgr.LANInfo()}+ },+ SubmitText: func(ctx context.Context, text string) (store.Clip, error) {+ // 手机本机的内容:不写回手机自己的剪贴板+ return engine.SubmitLocal(ctx, clipboard.Content{Kind: clipboard.KindText, Text: text}, "", false)+ },+ }, hub, token)++ go func() {+ for {+ select {+ case <-ctx.Done():+ return+ case <-statusDirty:+ if st, err := srv.GetStatus(ctx, &pb.Empty{}); err == nil {+ hub.Publish(rpc.EventStatusChanged(st))+ }+ }+ }+ }()++ port, grpcServer, err := srv.Serve(ctx)+ if err != nil {+ return nil, err+ }+ c.grpc = grpcServer+ if err := rpc.WriteEndpoint(paths.Endpoint, rpc.Endpoint{Port: port, Token: token, PID: os.Getpid(), Version: version}); err != nil {+ return nil, fmt.Errorf("写 daemon.json: %w", err)+ }+ notify.online(peerMgr)+ slog.Info("隔空贴核心就绪", "port", port, "data", paths.Root)+ return c, nil+}++// statusNotifier 把在线的电脑与最近收到的内容告诉宿主,宿主更新常驻通知。只报名字和类型,不报内容。+type statusNotifier struct {+ host Host+ mu gosync.Mutex+ names string+ lastFrom string+ lastKind string+}++func newStatusNotifier(h Host) *statusNotifier { return &statusNotifier{host: h} }++func (n *statusNotifier) online(m *peers.Manager) {+ _, list := m.Devices()+ var names []string+ for _, d := range list {+ if d.GetOnline() {+ names = append(names, d.GetName())+ }+ }+ n.mu.Lock()+ n.names = strings.Join(names, "\n")+ n.mu.Unlock()+ n.push()+}++func (n *statusNotifier) received(r *pb.ClipRecord) {+ kind := "file"+ switch r.GetKind() {+ case pb.ClipKind_CLIP_KIND_TEXT, pb.ClipKind_CLIP_KIND_HTML:+ kind = "text"+ case pb.ClipKind_CLIP_KIND_IMAGE:+ kind = "image"+ }+ n.mu.Lock()+ n.lastFrom, n.lastKind = r.GetOriginDeviceName(), kind+ n.mu.Unlock()+ n.push()+}++func (n *statusNotifier) push() {+ n.mu.Lock()+ names, from, kind := n.names, n.lastFrom, n.lastKind+ n.mu.Unlock()+ n.host.StatusChanged(names, from, kind)+}diff --git a/client-core/mobile/mobile_test.go b/client-core/mobile/mobile_test.gonew file mode 100644index 0000000..a8a1a8b--- /dev/null+++ b/client-core/mobile/mobile_test.go@@ -0,0 +1,135 @@+package mobile++import (+ "context"+ "fmt"+ "runtime"+ gosync "sync"+ "testing"+ "time"++ "google.golang.org/grpc"+ "google.golang.org/grpc/credentials/insecure"+ "google.golang.org/grpc/metadata"++ "github.com/baiyuze/pasteferry/client-core/internal/config"+ "github.com/baiyuze/pasteferry/client-core/internal/rpc"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++type fakeHost struct {+ mu gosync.Mutex+ writes []string+ online []string+}++func (h *fakeHost) WriteClipboard(kind, text, html, paths string) error {+ h.mu.Lock()+ defer h.mu.Unlock()+ h.writes = append(h.writes, kind+":"+text+paths)+ return nil+}++func (h *fakeHost) StatusChanged(online, lastFrom, lastKind string) {+ h.mu.Lock()+ defer h.mu.Unlock()+ h.online = append(h.online, online)+}++func dial(t *testing.T, dir string) (pb.DaemonServiceClient, context.Context) {+ t.Helper()+ ep, err := rpc.ReadEndpoint(config.PathsUnder(dir).Endpoint)+ if err != nil {+ t.Fatal(err)+ }+ conn, err := grpc.NewClient(fmt.Sprintf("127.0.0.1:%d", ep.Port), grpc.WithTransportCredentials(insecure.NewCredentials()))+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { conn.Close() })+ ctx := metadata.AppendToOutgoingContext(context.Background(), "x-pasteferry-token", ep.Token)+ return pb.NewDaemonServiceClient(conn), ctx+}++func TestStartServesGRPCAndStopsCleanly(t *testing.T) {+ dir := t.TempDir()+ host := &fakeHost{}+ before := runtime.NumGoroutine()+ if err := Start(dir, "Pixel 8", "2.7.0", host); err != nil {+ t.Fatal(err)+ }+ if err := Start(dir, "Pixel 8", "2.7.0", host); err != nil || !Running() {+ t.Fatalf("重复 Start:%v,running=%v", err, Running())+ }+ client, ctx := dial(t, dir)+ st, err := client.GetStatus(ctx, &pb.Empty{})+ if err != nil {+ t.Fatal(err)+ }+ if st.GetVersion() != "2.7.0" || st.GetDeviceName() != "Pixel 8" {+ t.Errorf("状态 = 版本 %q 名字 %q", st.GetVersion(), st.GetDeviceName())+ }+ cfg, err := client.GetConfig(ctx, &pb.Empty{})+ if err != nil {+ t.Fatal(err)+ }+ if cfg.GetServiceMode() != pb.ServiceMode_SERVICE_MODE_LAN {+ t.Errorf("服务模式 = %q,一期应只走局域网", cfg.GetServiceMode())+ }++ rec, err := client.SubmitText(ctx, &pb.SubmitTextRequest{Text: "手机上输入的文字"})+ if err != nil {+ t.Fatal(err)+ }+ if !rec.GetOutgoing() || rec.GetTextPreview() != "手机上输入的文字" {+ t.Errorf("发出的记录 = %v", rec)+ }+ hist, err := client.ListHistory(ctx, &pb.ListHistoryRequest{Limit: 10})+ if err != nil || len(hist.GetRecords()) != 1 {+ t.Fatalf("复制记录 = %v, %v", hist.GetRecords(), err)+ }+ // 发送页的文字不写回手机自己的剪贴板;「复制」才写+ host.mu.Lock()+ writes := len(host.writes)+ host.mu.Unlock()+ if writes != 0 {+ t.Errorf("发出的文字写进了手机剪贴板 %d 次", writes)+ }+ if _, err := client.ApplyToClipboard(ctx, &pb.ApplyToClipboardRequest{ClipId: rec.GetId()}); err != nil {+ t.Fatal(err)+ }+ host.mu.Lock()+ got := append([]string(nil), host.writes...)+ host.mu.Unlock()+ if len(got) != 1 || got[0] != "text:手机上输入的文字" {+ t.Errorf("复制 → 宿主收到 %v", got)+ }++ Stop()+ if Running() {+ t.Fatal("Stop 之后还在运行")+ }+ if _, err := client.GetStatus(ctx, &pb.Empty{}); err == nil {+ t.Error("Stop 之后 gRPC 还能连")+ }+ // 再启动一次:同一个数据目录,记录还在+ if err := Start(dir, "Pixel 8", "2.7.0", host); err != nil {+ t.Fatal(err)+ }+ client2, ctx2 := dial(t, dir)+ hist, err = client2.ListHistory(ctx2, &pb.ListHistoryRequest{Limit: 10})+ if err != nil || len(hist.GetRecords()) != 1 {+ t.Fatalf("重启后的复制记录 = %v, %v", hist.GetRecords(), err)+ }+ Stop()++ // 停止后不应残留大量 goroutine(允许少量运行时与 gRPC 的后台协程收尾)+ deadline := time.Now().Add(5 * time.Second)+ for runtime.NumGoroutine() > before+8 && time.Now().Before(deadline) {+ time.Sleep(100 * time.Millisecond)+ }+ if n := runtime.NumGoroutine(); n > before+8 {+ buf := make([]byte, 1<<16)+ t.Errorf("停止后还剩 %d 个 goroutine(启动前 %d)\n%s", n, before, buf[:runtime.Stack(buf, true)])+ }+}diff --git a/client-core/third_party/pion-mdns/LICENSE b/client-core/third_party/pion-mdns/LICENSEnew file mode 100644index 0000000..ab60297--- /dev/null+++ b/client-core/third_party/pion-mdns/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2018++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/client-core/third_party/pion-mdns/LICENSES/MIT.txt b/client-core/third_party/pion-mdns/LICENSES/MIT.txtnew file mode 100644index 0000000..2071b23--- /dev/null+++ b/client-core/third_party/pion-mdns/LICENSES/MIT.txt@@ -0,0 +1,9 @@+MIT License++Copyright (c) <year> <copyright holders>++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/client-core/third_party/pion-mdns/PASTEFERRY.md b/client-core/third_party/pion-mdns/PASTEFERRY.mdnew file mode 100644index 0000000..7274d8f--- /dev/null+++ b/client-core/third_party/pion-mdns/PASTEFERRY.md@@ -0,0 +1,13 @@+# pion/mdns v2.2.2,带一处改动++来源:github.com/pion/mdns/v2 v2.2.2(MIT,见 LICENSE),只复制了非测试的源文件。++改动只有 `server.go` 里取网卡和网卡地址的两行:`net.Interfaces()` 换成 `anet.Interfaces()`,+`ifc.Addrs()` 换成 `anet.InterfaceAddrsByInterface(&ifc)`。++原因:Android 11 起 App 不能对 NETLINK_ROUTE 套接字 bind,也不能用 RTM_GETLINK,+Go 标准库的这两个函数在 Android 上都报 `route ip+net: netlinkrib: permission denied`,+mDNS 起不来,手机发现不了局域网里的电脑(design/phone-sync.md 3.3.2 节第 3 条)。+其他平台上 anet 直接调用标准库,行为不变。++`client-core/go.mod` 用 replace 指到这里。上游修好、或者 pion/mdns 能让调用方传入地址后,删掉这个目录和 replace。diff --git a/client-core/third_party/pion-mdns/README.md b/client-core/third_party/pion-mdns/README.mdnew file mode 100644index 0000000..8b94e04--- /dev/null+++ b/client-core/third_party/pion-mdns/README.md@@ -0,0 +1,72 @@+<h1 align="center">+ <br>+ Pion mDNS+ <br>+</h1>+<h4 align="center">A Go implementation of mDNS</h4>+<p align="center">+ <a href="https://pion.ly"><img src="https://img.shields.io/badge/pion-mdns-gray.svg?longCache=true&colorB=brightgreen" alt="Pion mDNS"></a>+ <a href="https://discord.gg/PngbdqpFbt"><img src="https://img.shields.io/badge/join-us%20on%20discord-gray.svg?longCache=true&logo=discord&colorB=brightblue" alt="join us on Discord"></a> <a href="https://bsky.app/profile/pion.ly"><img src="https://img.shields.io/badge/follow-us%20on%20bluesky-gray.svg?longCache=true&logo=bluesky&colorB=brightblue" alt="Follow us on Bluesky"></a>+ <br>+ <img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pion/mdns/test.yaml">+ <a href="https://pkg.go.dev/github.com/pion/mdns"><img src="https://pkg.go.dev/badge/github.com/pion/mdsn.svg" alt="Go Reference"></a>+ <a href="https://codecov.io/gh/pion/mdns"><img src="https://codecov.io/gh/pion/mdns/branch/master/graph/badge.svg" alt="Coverage Status"></a>+ <a href="https://goreportcard.com/report/github.com/pion/mdns"><img src="https://goreportcard.com/badge/github.com/pion/mdns" alt="Go Report Card"></a>+ <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>+</p>+<br>++Go mDNS implementation. The original user is Pion WebRTC, but we would love to see it work for everyone.++### Running Server+For a mDNS server that responds to queries for `pion-test.local`+```sh+go run examples/server/main.go+```++For a mDNS server that responds to queries for `pion-test.local` with a given address+```sh+go run examples/server/publish_ip/main.go -ip=[IP]+```+If you don't set the `ip` parameter, "1.2.3.4" will be used instead.+++### Running Client+To query using Pion you can run the `query` example+```sh+go run examples/query/main.go+```++You can use the macOS client+```+dns-sd -q pion-test.local+```++Or the avahi client+```+avahi-resolve -a pion-test.local+```++### RFCs+#### Implemented+- **RFC 6762** [Multicast DNS][rfc6762]+- **draft-ietf-rtcweb-mdns-ice-candidates-02** [Using Multicast DNS to protect privacy when exposing ICE candidates](https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-mdns-ice-candidates-02.html)++[rfc6762]: https://tools.ietf.org/html/rfc6762++### Roadmap+The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones.++### Community+Pion has an active community on the [Discord](https://discord.gg/PngbdqpFbt).++Follow the [Pion Bluesky](https://bsky.app/profile/pion.ly) or [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news.++We are always looking to support **your projects**. Please reach out if you have something to build!+If you need commercial support or don't want to use public methods you can contact us at [[email protected]](mailto:[email protected])++### Contributing+Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible++### License+MIT License - see [LICENSE](LICENSE) for full text\ No newline at end of filediff --git a/client-core/third_party/pion-mdns/cache.go b/client-core/third_party/pion-mdns/cache.gonew file mode 100644index 0000000..0b41d63--- /dev/null+++ b/client-core/third_party/pion-mdns/cache.go@@ -0,0 +1,454 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "math/rand"+ "strings"+ "sync"+ "time"++ "golang.org/x/net/dns/dnsmessage"+)++// rrClassCacheFlush is the cache-flush bit in the rrclass field of a+// resource record (RFC 6762 §10.2).+const rrClassCacheFlush = 1 << 15++// goodbyeTTL is the time-to-live for goodbye packets (RFC 6762 §10.1).+// Records with TTL=0 are retained for one second before removal.+const goodbyeTTL = 1 * time.Second++// cacheFlushDelay is the grace period before flushing stale records+// after receiving a cache-flush response (RFC 6762 §10.2).+const cacheFlushDelay = 1 * time.Second++// maxRecordTTL caps the lifetime of cached records. RFC 6762 §10+// recommends TTLs of 75 minutes or less; clamping protects against+// hostile or misconfigured responders advertising near-immortal records.+const maxRecordTTL = 75 * time.Minute++// maxCacheEntries caps the total number of cached records so that a busy+// or hostile network cannot grow the cache without bound. When full, the+// entry closest to expiry is evicted to make room.+const maxCacheEntries = 4096++// cacheKey identifies a set of records by lowercased name, type, and+// class (with the cache-flush bit masked).+type cacheKey struct {+ name string+ rrType dnsmessage.Type+ rrClass dnsmessage.Class+}++// cacheEntry stores one cached resource record with timing metadata.+type cacheEntry struct {+ resource dnsmessage.Resource+ createdAt time.Time+ expiresAt time.Time+ originalTTL time.Duration+ refreshJitter float64+ refreshesSent uint8+}++// cache is a thread-safe mDNS record cache (RFC 6762 §10).+type cache struct {+ mu sync.RWMutex+ entries map[cacheKey][]cacheEntry+ size int+ now func() time.Time+}++// newCache creates a cache with the given clock function.+func newCache(now func() time.Time) *cache {+ return &cache{+ entries: make(map[cacheKey][]cacheEntry),+ now: now,+ }+}++// makeCacheKey builds a cache key from a resource header.+// The name is lowercased for case-insensitive matching.+func makeCacheKey(hdr dnsmessage.ResourceHeader) cacheKey {+ return cacheKey{+ name: strings.ToLower(hdr.Name.String()),+ rrType: hdr.Type,+ rrClass: hdr.Class,+ }+}++// insert adds or updates a record in the cache. It handles goodbye+// packets (TTL=0, §10.1), the cache-flush bit (§10.2), and normal+// insert/update operations.+func (c *cache) insert(res dnsmessage.Resource, receivedAt time.Time) {+ c.mu.Lock()+ defer c.mu.Unlock()++ hasCacheFlush := res.Header.Class&rrClassCacheFlush != 0+ res.Header.Class &^= rrClassCacheFlush++ key := makeCacheKey(res.Header)++ if res.Header.TTL == 0 {+ c.insertGoodbye(key, res, receivedAt)++ return+ }++ if hasCacheFlush {+ c.applyCacheFlush(key, receivedAt)+ }++ c.insertOrUpdate(key, res, receivedAt)+}++// insertGoodbye handles a record with TTL=0 (RFC 6762 §10.1).+// If a matching record exists, its expiry is set to now+1s.+// Otherwise a new entry is created with a 1s TTL. Goodbye entries+// keep originalTTL=0 so they are never refresh candidates.+func (c *cache) insertGoodbye(key cacheKey, res dnsmessage.Resource, receivedAt time.Time) {+ entries := c.entries[key]+ for idx := range entries {+ if resourceDataEqual(entries[idx].resource, res) {+ entries[idx].expiresAt = receivedAt.Add(goodbyeTTL)+ entries[idx].originalTTL = 0++ return+ }+ }++ // Unknown record: insert with 1s TTL so that late listeners see+ // the goodbye briefly before it expires.+ res.Header.TTL = 1+ c.appendEntry(key, cacheEntry{+ resource: res,+ createdAt: receivedAt,+ expiresAt: receivedAt.Add(goodbyeTTL),+ })+}++// applyCacheFlush marks old entries for the same key as expiring in 1s+// (RFC 6762 §10.2). Entries created within the last second are preserved.+func (c *cache) applyCacheFlush(key cacheKey, receivedAt time.Time) {+ entries := c.entries[key]+ deadline := receivedAt.Add(-cacheFlushDelay)++ for idx := range entries {+ if entries[idx].createdAt.Before(deadline) {+ entries[idx].expiresAt = receivedAt.Add(cacheFlushDelay)+ }+ }+}++// insertOrUpdate adds a new record or updates the TTL of an existing+// record with the same rdata. TTLs are clamped to maxRecordTTL.+func (c *cache) insertOrUpdate(key cacheKey, res dnsmessage.Resource, receivedAt time.Time) {+ ttl := min(time.Duration(res.Header.TTL)*time.Second, maxRecordTTL)+ entries := c.entries[key]++ for idx := range entries {+ if resourceDataEqual(entries[idx].resource, res) {+ entries[idx].resource.Header.TTL = res.Header.TTL+ entries[idx].createdAt = receivedAt+ entries[idx].expiresAt = receivedAt.Add(ttl)+ entries[idx].originalTTL = ttl+ entries[idx].refreshJitter = newRefreshJitter()+ entries[idx].refreshesSent = 0++ return+ }+ }++ c.appendEntry(key, cacheEntry{+ resource: res,+ createdAt: receivedAt,+ expiresAt: receivedAt.Add(ttl),+ originalTTL: ttl,+ refreshJitter: newRefreshJitter(),+ })+}++// appendEntry adds a new entry under key, evicting the entry closest to+// expiry when the cache is at capacity.+func (c *cache) appendEntry(key cacheKey, entry cacheEntry) {+ if c.size >= maxCacheEntries {+ c.evictSoonestExpiring()+ }++ c.entries[key] = append(c.entries[key], entry)+ c.size+++}++// evictSoonestExpiring removes the entry with the earliest expiry.+func (c *cache) evictSoonestExpiring() {+ var victimKey cacheKey+ victimIdx := -1+ var victimExpiry time.Time++ for key, entries := range c.entries {+ for idx := range entries {+ if victimIdx == -1 || entries[idx].expiresAt.Before(victimExpiry) {+ victimKey = key+ victimIdx = idx+ victimExpiry = entries[idx].expiresAt+ }+ }+ }++ if victimIdx == -1 {+ return+ }++ entries := c.entries[victimKey]+ entries = append(entries[:victimIdx], entries[victimIdx+1:]...)++ if len(entries) == 0 {+ delete(c.entries, victimKey)+ } else {+ c.entries[victimKey] = entries+ }++ c.size--+}++// lookup returns non-expired records matching the name, type, and class.+// The name match is case-insensitive. Each returned record has its TTL+// set to the remaining time before expiry.+func (c *cache) lookup(name string, rrType dnsmessage.Type, rrClass dnsmessage.Class) []dnsmessage.Resource {+ c.mu.RLock()+ defer c.mu.RUnlock()++ key := cacheKey{+ name: strings.ToLower(name),+ rrType: rrType,+ rrClass: rrClass,+ }++ now := c.now()+ var results []dnsmessage.Resource++ for _, entry := range c.entries[key] {+ if !now.Before(entry.expiresAt) {+ continue+ }++ res := entry.resource+ remaining := entry.expiresAt.Sub(now)+ res.Header.TTL = uint32(remaining / time.Second) //nolint:gosec // remaining is positive after expiry check+ results = append(results, res)+ }++ return results+}++// sweep removes all expired entries from the cache.+func (c *cache) sweep() {+ c.mu.Lock()+ defer c.mu.Unlock()++ now := c.now()+ size := 0++ for key, entries := range c.entries {+ var alive []cacheEntry++ for _, entry := range entries {+ if now.Before(entry.expiresAt) {+ alive = append(alive, entry)+ }+ }++ if len(alive) == 0 {+ delete(c.entries, key)+ } else {+ c.entries[key] = alive+ size += len(alive)+ }+ }++ c.size = size+}++// refreshThresholds returns the fractions of TTL at which refresh queries+// are sent (RFC 6762 §5.2): 80%, 85%, 90%, 95%.+func refreshThresholds() [4]float64 {+ return [4]float64{0.80, 0.85, 0.90, 0.95}+}++// maxRefreshJitter is the maximum random jitter added to each threshold.+const maxRefreshJitter = 0.02++// newRefreshJitter returns a random 0-2% addition to the next refresh+// threshold (RFC 6762 §5.2). Rolled once per threshold so that repeated+// polling does not bias refreshes toward the unjittered threshold.+func newRefreshJitter() float64 {+ return rand.Float64() * maxRefreshJitter //nolint:gosec // weak random is fine for jitter+}++// takeRefreshCandidates consumes and returns the keys with entries that+// have reached their next refresh threshold (RFC 6762 §5.2). Each returned+// candidate has its refreshesSent counter incremented under the cache lock,+// so a key is handed out at most once per threshold; the caller is expected+// to send the refresh query. Duplicate keys are checked once and a key is+// returned at most once per call, even when several entries under it are+// due (one question refreshes all records for the key). Entries with+// originalTTL = 0 (goodbyes) are skipped and at most four refreshes are+// handed out per entry per TTL.+func (c *cache) takeRefreshCandidates(keys []cacheKey) []cacheKey {+ c.mu.Lock()+ defer c.mu.Unlock()++ now := c.now()+ thresholds := refreshThresholds()++ var candidates []cacheKey+ seen := make(map[cacheKey]struct{}, len(keys))++ for _, key := range keys {+ if _, dup := seen[key]; dup {+ continue+ }+ seen[key] = struct{}{}++ entries := c.entries[key]+ keyAdded := false+ for idx := range entries {+ entry := &entries[idx]+ if entry.originalTTL <= 0 || int(entry.refreshesSent) >= len(thresholds) {+ continue+ }++ if !now.Before(entry.expiresAt) {+ continue+ }++ startedAt := entry.expiresAt.Add(-entry.originalTTL)+ fraction := float64(now.Sub(startedAt)) / float64(entry.originalTTL)++ if fraction >= thresholds[entry.refreshesSent]+entry.refreshJitter {+ if !keyAdded {+ candidates = append(candidates, key)+ keyAdded = true+ }+ entry.refreshesSent+++ entry.refreshJitter = newRefreshJitter()+ }+ }+ }++ return candidates+}++// flushAll drops all entries (RFC 6762 §10.3 topology change).+func (c *cache) flushAll() {+ c.mu.Lock()+ defer c.mu.Unlock()++ c.entries = make(map[cacheKey][]cacheEntry)+ c.size = 0+}++// reduceTTLs caps the remaining TTL of every entry to maxRemaining.+// Entries that already expire sooner are left unchanged.+func (c *cache) reduceTTLs(maxRemaining time.Duration) {+ c.mu.Lock()+ defer c.mu.Unlock()++ now := c.now()+ deadline := now.Add(maxRemaining)++ for _, entries := range c.entries {+ for idx := range entries {+ if entries[idx].expiresAt.After(deadline) {+ entries[idx].expiresAt = deadline+ }+ }+ }+}++// len returns the count of non-expired entries.+func (c *cache) len() int {+ c.mu.RLock()+ defer c.mu.RUnlock()++ now := c.now()+ count := 0++ for _, entries := range c.entries {+ for _, entry := range entries {+ if now.Before(entry.expiresAt) {+ count+++ }+ }+ }++ return count+}++// resourceDataEqual reports whether two resources have the same name,+// type, and body content. Name comparison is case-insensitive.+func resourceDataEqual(resA, resB dnsmessage.Resource) bool {+ if !strings.EqualFold(resA.Header.Name.String(), resB.Header.Name.String()) {+ return false+ }++ if resA.Header.Type != resB.Header.Type {+ return false+ }++ return resourceBodyEqual(resA.Body, resB.Body)+}++// resourceBodyEqual compares two resource bodies by type-specific fields.+//+//nolint:cyclop+func resourceBodyEqual(bodyA, bodyB dnsmessage.ResourceBody) bool {+ switch valA := bodyA.(type) {+ case *dnsmessage.AResource:+ valB, ok := bodyB.(*dnsmessage.AResource)++ return ok && valA.A == valB.A+ case *dnsmessage.AAAAResource:+ valB, ok := bodyB.(*dnsmessage.AAAAResource)++ return ok && valA.AAAA == valB.AAAA+ case *dnsmessage.PTRResource:+ valB, ok := bodyB.(*dnsmessage.PTRResource)++ return ok && strings.EqualFold(valA.PTR.String(), valB.PTR.String())+ case *dnsmessage.SRVResource:+ valB, ok := bodyB.(*dnsmessage.SRVResource)++ return ok && srvFieldsEqual(valA, valB)+ case *dnsmessage.TXTResource:+ valB, ok := bodyB.(*dnsmessage.TXTResource)++ return ok && txtSlicesEqual(valA.TXT, valB.TXT)+ default:+ return false+ }+}++// srvFieldsEqual compares two SRV resource bodies field by field.+func srvFieldsEqual(resA, resB *dnsmessage.SRVResource) bool {+ return strings.EqualFold(resA.Target.String(), resB.Target.String()) &&+ resA.Port == resB.Port &&+ resA.Priority == resB.Priority &&+ resA.Weight == resB.Weight+}++// txtSlicesEqual reports whether two TXT string slices are identical.+func txtSlicesEqual(sliceA, sliceB []string) bool {+ if len(sliceA) != len(sliceB) {+ return false+ }++ for idx := range sliceA {+ if sliceA[idx] != sliceB[idx] {+ return false+ }+ }++ return true+}diff --git a/client-core/third_party/pion-mdns/client.go b/client-core/third_party/pion-mdns/client.gonew file mode 100644index 0000000..bbd7649--- /dev/null+++ b/client-core/third_party/pion-mdns/client.go@@ -0,0 +1,806 @@+// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "context"+ "errors"+ "net"+ "net/netip"+ "strings"+ "sync"+ "time"++ "github.com/pion/logging"+ "golang.org/x/net/dns/dnsmessage"+)++// qClassUnicastResponse is the bit flag for the unicast-response bit in the+// Question Section qclass field (RFC 6762, Section 18.12).+const qClassUnicastResponse = 1 << 15++var (+ errFailedToDecodeAddrFromAResource = errors.New("failed to decode netip.Addr from A type Resource")+ errFailedToDecodeAddrFromAAAAResource = errors.New("failed to decode netip.Addr from AAAA type Resource")+ errUnhandledAnswerHeaderType = errors.New("header for Answer had unhandled type")+)++// messageContext carries metadata about a received mDNS packet.+type messageContext struct {+ // source is the address the packet was received from.+ source *net.UDPAddr+ // ifIndex is the interface index the packet was received on (-1 if unknown).+ ifIndex int+ // pktDst is the destination address of the packet (for unicast detection).+ pktDst net.IP+ // timestamp is when the packet was received.+ timestamp time.Time+}++// questionWriter is the interface for sending DNS questions.+type questionWriter interface {+ writeQuestion(b []byte)+}++// client handles mDNS client operations (querying).+type client struct {+ log logging.LeveledLogger+ name string+ handler *answerHandler+ writer questionWriter+ hasIPv4 bool+ hasIPv6 bool+}++// newClient creates a new mDNS client.+func newClient(+ log logging.LeveledLogger,+ name string,+ writer questionWriter,+ hasIPv4, hasIPv6 bool,+ recordCache *cache,+) *client {+ return &client{+ log: log,+ name: name,+ handler: newAnswerHandler(log, name, recordCache),+ writer: writer,+ hasIPv4: hasIPv4,+ hasIPv6: hasIPv6,+ }+}++// sendQuestion sends mDNS queries for the given name.+func (c *client) sendQuestion(name string) {+ packedName, err := dnsmessage.NewName(name)+ if err != nil {+ c.log.Warnf("[%s] failed to construct mDNS packet %v", c.name, err)++ return+ }++ // Limit queries to the available address families.+ var types []dnsmessage.Type+ if c.hasIPv4 {+ types = append(types, dnsmessage.TypeA)+ }+ if c.hasIPv6 {+ types = append(types, dnsmessage.TypeAAAA)+ }++ // Chromium responders reject queries with multiple questions or the+ // unicast-response bit set. Send each question separately with plain IN.+ // https://chromium.googlesource.com/chromium/src/+/684d13ecf02435a8920a41283e442c6e1a13e5b4/net/dns/dns_query.cc#217+ // https://chromium.googlesource.com/chromium/src/+/684d13ecf02435a8920a41283e442c6e1a13e5b4/net/dns/dns_query.cc#228+ for _, recordType := range types {+ msg := dnsmessage.Message{+ Questions: []dnsmessage.Question{{+ Type: recordType,+ Class: dnsmessage.ClassINET,+ Name: packedName,+ }},+ }+ rawQuery, err := msg.Pack()+ if err != nil {+ c.log.Warnf("[%s] failed to construct mDNS packet %v", c.name, err)++ return+ }++ c.writer.writeQuestion(rawQuery)+ }+}++// sendBrowseQuestion sends a PTR query for a DNS-SD service type.+func (c *client) sendBrowseQuestion(serviceName string) {+ packedName, err := dnsmessage.NewName(serviceName)+ if err != nil {+ c.log.Warnf("[%s] failed to construct browse query name %v", c.name, err)++ return+ }++ msg := dnsmessage.Message{+ Header: dnsmessage.Header{},+ Questions: []dnsmessage.Question{+ {+ Type: dnsmessage.TypePTR,+ Class: dnsmessage.ClassINET,+ Name: packedName,+ },+ },+ }++ rawQuery, err := msg.Pack()+ if err != nil {+ c.log.Warnf("[%s] failed to pack browse query %v", c.name, err)++ return+ }++ c.writer.writeQuestion(rawQuery)+}++// sendEnumerateQuestion sends a PTR query for the service type enumeration+// meta-query (RFC 6763 §9).+func (c *client) sendEnumerateQuestion(domain string) {+ name := serviceTypeEnumerationName + "." + domain + "."+ packedName, err := dnsmessage.NewName(name)+ if err != nil {+ c.log.Warnf("[%s] failed to construct enumerate query name %v", c.name, err)++ return+ }++ msg := dnsmessage.Message{+ Header: dnsmessage.Header{},+ Questions: []dnsmessage.Question{+ {+ Type: dnsmessage.TypePTR,+ Class: dnsmessage.ClassINET,+ Name: packedName,+ },+ },+ }++ rawQuery, err := msg.Pack()+ if err != nil {+ c.log.Warnf("[%s] failed to pack enumerate query %v", c.name, err)++ return+ }++ c.writer.writeQuestion(rawQuery)+}++// answerHandler processes incoming mDNS answers (client role).+// It matches answers against registered queries and delivers results.+// It also processes answers for active browse and enumerate sessions.+type answerHandler struct {+ mu sync.RWMutex+ queries []*query+ browseSessions []*browseSession+ enumerateSessions []*enumerateSession+ log logging.LeveledLogger+ name string+ cache *cache+}++// newAnswerHandler creates a new answerHandler.+func newAnswerHandler(log logging.LeveledLogger, name string, recordCache *cache) *answerHandler {+ return &answerHandler{+ log: log,+ name: name,+ cache: recordCache,+ }+}++// registerQuery adds a query to be matched against incoming answers.+// Returns the query so it can be unregistered later.+func (h *answerHandler) registerQuery(nameWithSuffix string, resultChan chan queryResult) *query {+ q := &query{+ nameWithSuffix: nameWithSuffix,+ queryResultChan: resultChan,+ }+ h.mu.Lock()+ h.queries = append(h.queries, q)+ h.mu.Unlock()++ return q+}++// unregisterQuery removes a query from the handler.+func (h *answerHandler) unregisterQuery(q *query) {+ h.mu.Lock()+ defer h.mu.Unlock()+ for i := len(h.queries) - 1; i >= 0; i-- {+ if h.queries[i] == q {+ h.queries = append(h.queries[:i], h.queries[i+1:]...)+ }+ }+}++// registerBrowseSession adds a browse session to be matched against incoming answers.+func (h *answerHandler) registerBrowseSession(session *browseSession) {+ h.mu.Lock()+ h.browseSessions = append(h.browseSessions, session)+ h.mu.Unlock()+}++// unregisterBrowseSession removes a browse session from the handler.+func (h *answerHandler) unregisterBrowseSession(session *browseSession) {+ h.mu.Lock()+ defer h.mu.Unlock()+ for i := len(h.browseSessions) - 1; i >= 0; i-- {+ if h.browseSessions[i] == session {+ h.browseSessions = append(h.browseSessions[:i], h.browseSessions[i+1:]...)+ }+ }+}++// registerEnumerateSession adds an enumerate session to be matched against incoming answers.+func (h *answerHandler) registerEnumerateSession(session *enumerateSession) {+ h.mu.Lock()+ h.enumerateSessions = append(h.enumerateSessions, session)+ h.mu.Unlock()+}++// unregisterEnumerateSession removes an enumerate session from the handler.+func (h *answerHandler) unregisterEnumerateSession(session *enumerateSession) {+ h.mu.Lock()+ defer h.mu.Unlock()+ for i := len(h.enumerateSessions) - 1; i >= 0; i-- {+ if h.enumerateSessions[i] == session {+ h.enumerateSessions = append(h.enumerateSessions[:i], h.enumerateSessions[i+1:]...)+ }+ }+}++// monitoredCacheKeys returns cache keys for all actively-monitored records+// across browse and enumerate sessions.+func (h *answerHandler) monitoredCacheKeys() []cacheKey {+ h.mu.RLock()+ browseSessions := make([]*browseSession, len(h.browseSessions))+ copy(browseSessions, h.browseSessions)+ enumerateSessions := make([]*enumerateSession, len(h.enumerateSessions))+ copy(enumerateSessions, h.enumerateSessions)+ h.mu.RUnlock()++ var keys []cacheKey++ for _, session := range browseSessions {+ keys = append(keys, session.monitoredCacheKeys()...)+ }++ for _, session := range enumerateSessions {+ keys = append(keys, session.monitoredCacheKeys()...)+ }++ return keys+}++// handle processes a DNS message containing answers.+// It matches answers against registered name queries, active browse sessions,+// and active enumerate sessions.+//+//nolint:cyclop,gocognit+func (h *answerHandler) handle(ctx *messageContext, msg *dnsmessage.Message) {+ h.mu.RLock()+ queries := make([]*query, len(h.queries))+ copy(queries, h.queries)+ browseSessions := make([]*browseSession, len(h.browseSessions))+ copy(browseSessions, h.browseSessions)+ enumerateSessions := make([]*enumerateSession, len(h.enumerateSessions))+ copy(enumerateSessions, h.enumerateSessions)+ h.mu.RUnlock()++ // Process all records (Answers + Additionals) for browse and enumerate sessions.+ allRecords := make([]dnsmessage.Resource, 0, len(msg.Answers)+len(msg.Additionals))+ allRecords = append(allRecords, msg.Answers...)+ allRecords = append(allRecords, msg.Additionals...)++ // Insert all received records into the cache.+ for _, record := range allRecords {+ h.cache.insert(record, ctx.timestamp)+ }++ for _, answer := range allRecords {+ // Match against browse sessions (all record types).+ for _, session := range browseSessions {+ session.processRecord(answer, ctx.source.Zone)+ }++ // Match against enumerate sessions (PTR only).+ for _, session := range enumerateSessions {+ session.processRecord(answer)+ }+ }++ // Match A/AAAA answers against registered name queries (existing behavior).+ for _, answer := range msg.Answers {+ if answer.Header.Type != dnsmessage.TypeA && answer.Header.Type != dnsmessage.TypeAAAA {+ continue+ }++ var answered []*query+ for _, q := range queries {+ queryCopy := q+ if !strings.EqualFold(queryCopy.nameWithSuffix, answer.Header.Name.String()) {+ continue+ }++ addr, err := addrFromAnswer(answer)+ if err != nil {+ h.log.Warnf("[%s] failed to parse mDNS answer %v", h.name, err)++ continue+ }++ resultAddr := *addr+ // DNS records don't contain IPv6 zones.+ // Trust that link-local addresses are from the source's interface.+ resultAddr = addrWithOptionalZone(resultAddr, ctx.source.Zone)++ select {+ case queryCopy.queryResultChan <- queryResult{answer.Header, resultAddr}:+ answered = append(answered, queryCopy)+ default:+ }+ }++ // Remove answered queries.+ h.mu.Lock()+ for queryIdx := len(h.queries) - 1; queryIdx >= 0; queryIdx-- {+ for answerIdx := len(answered) - 1; answerIdx >= 0; answerIdx-- {+ if h.queries[queryIdx] == answered[answerIdx] {+ h.queries = append(h.queries[:queryIdx], h.queries[queryIdx+1:]...)+ answered = append(answered[:answerIdx], answered[answerIdx+1:]...)++ break+ }+ }+ }+ h.mu.Unlock()+ }+}++// pendingInstance tracks a partially-resolved DNS-SD service instance.+// A browse session collects PTR → SRV + TXT → A/AAAA records before emitting+// a complete ServiceEvent.+type pendingInstance struct {+ instance string // from PTR rdata+ service string+ domain string+ host string+ port uint16+ priority uint16+ weight uint16+ text []TXTEntry+ addr netip.Addr+ hasSRV bool+ hasTXT bool+ hasAddr bool+}++// isComplete returns true when all required records have been resolved.+func (p *pendingInstance) isComplete() bool {+ return p.hasSRV && p.hasTXT && p.hasAddr+}++// toServiceEvent converts a complete pending instance to a ServiceEvent.+func (p *pendingInstance) toServiceEvent() ServiceEvent {+ return ServiceEvent{+ Instance: ServiceInstance{+ Instance: p.instance,+ Service: p.service,+ Domain: p.domain,+ Host: p.host,+ Port: p.port,+ Priority: p.priority,+ Weight: p.weight,+ Text: p.text,+ },+ Addr: p.addr,+ }+}++// browseSession tracks the state of an active Browse call.+type browseSession struct {+ serviceType string // e.g. "_http._tcp"+ domain string // e.g. "local"+ emit func(ServiceEvent)+ seen map[string]ServiceEvent // last event emitted for each instance+ pending map[string]*pendingInstance // instances being assembled+ mu sync.Mutex+ done chan struct{}+ cancel context.CancelFunc+}++// newBrowseSession creates a new browse session.+func newBrowseSession(ctx context.Context, serviceType string, emit func(ServiceEvent)) *browseSession {+ sessionCtx, cancel := context.WithCancel(ctx)+ done := make(chan struct{})++ go func() {+ <-sessionCtx.Done()+ close(done)+ }()++ return &browseSession{+ serviceType: serviceType,+ domain: "local",+ emit: emit,+ seen: make(map[string]ServiceEvent),+ pending: make(map[string]*pendingInstance),+ done: done,+ cancel: cancel,+ }+}++// serviceName returns the fully-qualified browse query name.+func (bs *browseSession) serviceName() string {+ return bs.serviceType + "." + bs.domain + "."+}++// monitoredCacheKeys returns cache keys for records this browse session+// is actively monitoring: the PTR for the service type, plus SRV/TXT/A/AAAA+// keys for known instances.+func (bs *browseSession) monitoredCacheKeys() []cacheKey {+ bs.mu.Lock()+ defer bs.mu.Unlock()++ svcName := strings.ToLower(bs.serviceType + "." + bs.domain + ".")++ keys := []cacheKey{+ {name: svcName, rrType: dnsmessage.TypePTR, rrClass: dnsmessage.ClassINET},+ }++ // Add keys for pending instances.+ for _, inst := range bs.pending {+ keys = append(keys, bs.instanceCacheKeys(inst)...)+ }++ // Add keys for already-seen instances (they remain in the seen map).+ // We don't track full details for emitted instances, but the PTR key+ // above covers rediscovery.++ return keys+}++// instanceCacheKeys returns cache keys for a pending service instance.+func (bs *browseSession) instanceCacheKeys(inst *pendingInstance) []cacheKey {+ var keys []cacheKey++ instanceName := strings.ToLower(+ escapeInstanceName(inst.instance) + "." + inst.service + "." + inst.domain + ".",+ )+ keys = append(keys,+ cacheKey{name: instanceName, rrType: dnsmessage.TypeSRV, rrClass: dnsmessage.ClassINET},+ cacheKey{name: instanceName, rrType: dnsmessage.TypeTXT, rrClass: dnsmessage.ClassINET},+ )++ if inst.host != "" {+ hostName := strings.ToLower(inst.host)+ keys = append(keys,+ cacheKey{name: hostName, rrType: dnsmessage.TypeA, rrClass: dnsmessage.ClassINET},+ cacheKey{name: hostName, rrType: dnsmessage.TypeAAAA, rrClass: dnsmessage.ClassINET},+ )+ }++ return keys+}++// processRecord updates the browse session with a received DNS resource record.+// Returns true if a new complete instance was emitted.+//+//nolint:cyclop+func (bs *browseSession) processRecord(answer dnsmessage.Resource, zone string) bool {+ bs.mu.Lock()+ defer bs.mu.Unlock()++ switch answer.Header.Type {+ case dnsmessage.TypePTR:+ bs.handlePTRRecord(answer)++ return false+ case dnsmessage.TypeSRV:+ return bs.handleSRVRecord(answer, zone)+ case dnsmessage.TypeTXT:+ return bs.handleTXTRecord(answer)+ case dnsmessage.TypeA, dnsmessage.TypeAAAA:+ return bs.handleAddressRecord(answer, zone)+ default:+ return false+ }+}++// handlePTRRecord processes a PTR answer for this browse session.+func (bs *browseSession) handlePTRRecord(answer dnsmessage.Resource) {+ target, err := parsePTRTarget(answer.Body)+ if err != nil {+ return+ }++ instance, service, domain, err := parseServiceInstanceName(target)+ if err != nil {+ return+ }++ if _, exists := bs.pending[instance]; !exists {+ if _, seen := bs.seen[instance]; seen {+ return+ }+ bs.pending[instance] = &pendingInstance{+ instance: instance,+ service: service,+ domain: domain,+ }+ }+}++// handleSRVRecord processes an SRV answer.+func (bs *browseSession) handleSRVRecord(answer dnsmessage.Resource, zone string) bool {+ target, port, priority, weight, err := parseSRVData(answer.Body)+ if err != nil {+ return false+ }++ inst := bs.findPendingByInstanceName(answer.Header.Name.String())+ if inst == nil {+ return false+ }++ inst.host = target+ inst.port = port+ inst.priority = priority+ inst.weight = weight+ inst.hasSRV = true++ return bs.tryEmit(inst, zone)+}++// handleTXTRecord processes a TXT answer.+func (bs *browseSession) handleTXTRecord(answer dnsmessage.Resource) bool {+ txts, err := parseTXTData(answer.Body)+ if err != nil {+ return false+ }++ inst := bs.findPendingByInstanceName(answer.Header.Name.String())+ if inst == nil {+ return false+ }++ inst.text = decodeTXTRecordStrings(txts)+ inst.hasTXT = true++ return bs.tryEmit(inst, "")+}++// handleAddressRecord processes an A or AAAA answer.+func (bs *browseSession) handleAddressRecord(answer dnsmessage.Resource, zone string) bool {+ addr, err := addrFromAnswer(answer)+ if err != nil {+ return false+ }++ resultAddr := addrWithOptionalZone(*addr, zone)++ // Match against any pending instance whose host matches this answer name.+ answerName := answer.Header.Name.String()+ emitted := false+ for _, inst := range bs.pending {+ if !inst.hasSRV {+ continue+ }+ if !strings.EqualFold(inst.host, answerName) {+ continue+ }++ inst.addr = resultAddr+ inst.hasAddr = true++ if bs.tryEmit(inst, zone) {+ emitted = true+ }+ }++ return emitted+}++// findPendingByInstanceName finds a pending instance matching the given FQDN.+func (bs *browseSession) findPendingByInstanceName(name string) *pendingInstance {+ for _, inst := range bs.pending {+ fqdn := inst.instance+ if inst.service != "" {+ fqdn = escapeInstanceName(inst.instance) + "." + inst.service + "." + inst.domain + "."+ }+ if strings.EqualFold(fqdn, name) {+ return inst+ }+ }++ return nil+}++// tryEmit fires the callback when a complete instance is first resolved or changes.+func (bs *browseSession) tryEmit(inst *pendingInstance, zone string) bool {+ if !inst.isComplete() {+ return false+ }++ if zone != "" {+ inst.addr = addrWithOptionalZone(inst.addr, zone)+ }++ evt := inst.toServiceEvent()+ previous, seen := bs.seen[inst.instance]+ if seen && serviceEventsEqual(previous, evt) {+ return false+ }+ if seen {+ evt.Type = ServiceUpdated+ } else {+ evt.Type = ServiceAdded+ }+ bs.seen[inst.instance] = cloneServiceEvent(evt)+ bs.emit(cloneServiceEvent(evt))++ return true+}++func serviceEventsEqual(a, b ServiceEvent) bool {+ return a.Addr == b.Addr &&+ a.Instance.Instance == b.Instance.Instance &&+ a.Instance.Service == b.Instance.Service &&+ a.Instance.Domain == b.Instance.Domain &&+ a.Instance.Host == b.Instance.Host &&+ a.Instance.Port == b.Instance.Port &&+ a.Instance.Priority == b.Instance.Priority &&+ a.Instance.Weight == b.Instance.Weight &&+ txtEntriesEqual(a.Instance.Text, b.Instance.Text)+}++func cloneServiceEvent(evt ServiceEvent) ServiceEvent {+ cloned := evt+ cloned.Instance.Text = cloneTXTEntries(evt.Instance.Text)++ return cloned+}++// enumerateSession tracks the state of an active EnumerateServiceTypes call.+type enumerateSession struct {+ domain string+ emit func(string)+ seen map[string]bool+ mu sync.Mutex+ done chan struct{}+ cancel context.CancelFunc+}++// newEnumerateSession creates a new enumerate session.+func newEnumerateSession(ctx context.Context, emit func(string)) *enumerateSession {+ sessionCtx, cancel := context.WithCancel(ctx)+ done := make(chan struct{})++ go func() {+ <-sessionCtx.Done()+ close(done)+ }()++ return &enumerateSession{+ domain: "local",+ emit: emit,+ seen: make(map[string]bool),+ done: done,+ cancel: cancel,+ }+}++// monitoredCacheKeys returns the cache key for the service type enumeration+// meta-query PTR record.+func (es *enumerateSession) monitoredCacheKeys() []cacheKey {+ name := strings.ToLower(serviceTypeEnumerationName + "." + es.domain + ".")++ return []cacheKey{+ {name: name, rrType: dnsmessage.TypePTR, rrClass: dnsmessage.ClassINET},+ }+}++// processRecord handles a PTR answer for the service type enumeration meta-query.+func (es *enumerateSession) processRecord(answer dnsmessage.Resource) {+ if answer.Header.Type != dnsmessage.TypePTR {+ return+ }++ target, err := parsePTRTarget(answer.Body)+ if err != nil {+ return+ }++ // Target is like "_http._tcp.local." — extract the service type.+ target = strings.TrimSuffix(target, ".")+ parts := strings.SplitN(target, ".", 3)+ if len(parts) < 2 {+ return+ }+ serviceType := parts[0] + "." + parts[1]++ es.mu.Lock()+ defer es.mu.Unlock()++ if es.seen[serviceType] {+ return+ }+ es.seen[serviceType] = true++ es.emit(serviceType)+}++// maxRefreshQuestionsPerMessage caps how many questions are packed into a+// single refresh query message to stay well under the mDNS packet limit.+const maxRefreshQuestionsPerMessage = 10++// sendRefreshQuestions sends multicast DNS questions for the given cache+// keys, batching multiple questions per message (RFC 6762 §7.2). Used to+// refresh actively-monitored cache entries per RFC 6762 §5.2.+func (c *client) sendRefreshQuestions(keys []cacheKey) {+ questions := make([]dnsmessage.Question, 0, len(keys))++ for _, key := range keys {+ packedName, err := dnsmessage.NewName(key.name)+ if err != nil {+ c.log.Warnf("[%s] failed to construct refresh query name %v", c.name, err)++ continue+ }++ questions = append(questions, dnsmessage.Question{+ Type: key.rrType,+ Class: dnsmessage.ClassINET,+ Name: packedName,+ })+ }++ for start := 0; start < len(questions); start += maxRefreshQuestionsPerMessage {+ end := min(start+maxRefreshQuestionsPerMessage, len(questions))+ msg := dnsmessage.Message{Questions: questions[start:end]}++ rawQuery, err := msg.Pack()+ if err != nil {+ c.log.Warnf("[%s] failed to pack refresh query %v", c.name, err)++ continue+ }++ c.writer.writeQuestion(rawQuery)+ }+}++func addrFromAnswer(answer dnsmessage.Resource) (*netip.Addr, error) {+ switch answer.Header.Type {+ case dnsmessage.TypeA:+ if a, ok := answer.Body.(*dnsmessage.AResource); ok {+ addr, ok := netip.AddrFromSlice(a.A[:])+ if ok {+ addr = addr.Unmap() // do not want 4-in-6++ return &addr, nil+ }+ }++ return nil, errFailedToDecodeAddrFromAResource+ case dnsmessage.TypeAAAA:+ if a, ok := answer.Body.(*dnsmessage.AAAAResource); ok {+ addr, ok := netip.AddrFromSlice(a.AAAA[:])+ if ok {+ return &addr, nil+ }+ }++ return nil, errFailedToDecodeAddrFromAAAAResource+ default:+ return nil, errUnhandledAnswerHeaderType+ }+}diff --git a/client-core/third_party/pion-mdns/config.go b/client-core/third_party/pion-mdns/config.gonew file mode 100644index 0000000..d7b5681--- /dev/null+++ b/client-core/third_party/pion-mdns/config.go@@ -0,0 +1,346 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "errors"+ "net"+ "time"++ "github.com/pion/logging"+ "golang.org/x/net/dns/dnsmessage"+)++var (+ errResponseTTLZero = errors.New("response TTL must be greater than 0")+ errIntervalNonPositive = errors.New("time interval must be greater than 0")+)++const (+ // DefaultAddressIPv4 is the default used by mDNS+ // and in most cases should be the address that the+ // ipv4.PacketConn passed to Server or NewServer is bound to.+ DefaultAddressIPv4 = "224.0.0.0:5353"++ // DefaultAddressIPv6 is the default IPv6 address used+ // by mDNS and in most cases should be the address that+ // the ipv6.PacketConn passed to Server or NewServer is bound to.+ DefaultAddressIPv6 = "[FF02::]:5353"+)++// Config is used to configure a mDNS client or server.+type Config struct {+ // Name is the name of the client/server used for logging purposes.+ Name string++ // QueryInterval controls how often we sends Queries until we+ // get a response for the requested name.+ QueryInterval time.Duration++ // LocalNames are the names that we will generate answers for+ // when we get questions.+ LocalNames []string++ // LocalAddress will override the published address with the given IP+ // when set. Otherwise, the automatically determined address will be used.+ LocalAddress net.IP++ // LoggerFactory is used to create a logger for the server.+ LoggerFactory logging.LoggerFactory++ // IncludeLoopback will include loopback interfaces to be eligible for queries and answers.+ IncludeLoopback bool++ // Interfaces will override the interfaces used for queries and answers.+ Interfaces []net.Interface+}++// ServerOption configures a Server.+type ServerOption interface {+ applyServer(*serverConfig) error+}++// ClientOption configures a Client.+type ClientOption interface {+ applyClient(*clientConfig) error+}++// clientConfig holds configuration for a future dedicated Client type.+// Currently used to demonstrate shared options between Server and Client.+type clientConfig struct {+ name string+ queryInterval time.Duration+ loggerFactory logging.LoggerFactory+ includeLoopback bool+ interfaces []net.Interface+}++// nameOption sets the name for logging.+type nameOption string++// WithName sets the name used for logging purposes.+func WithName(name string) nameOption {+ return nameOption(name)+}++func (o nameOption) applyServer(c *serverConfig) error {+ c.name = string(o)++ return nil+}++func (o nameOption) applyClient(c *clientConfig) error {+ c.name = string(o)++ return nil+}++// loggerFactoryOption sets the logger factory.+type loggerFactoryOption struct {+ factory logging.LoggerFactory+}++// WithLoggerFactory sets the logger factory for creating loggers.+func WithLoggerFactory(factory logging.LoggerFactory) loggerFactoryOption {+ return loggerFactoryOption{factory: factory}+}++func (o loggerFactoryOption) applyServer(c *serverConfig) error {+ c.loggerFactory = o.factory++ return nil+}++func (o loggerFactoryOption) applyClient(c *clientConfig) error {+ c.loggerFactory = o.factory++ return nil+}++// includeLoopbackOption sets whether to include loopback interfaces.+type includeLoopbackOption bool++// WithIncludeLoopback sets whether loopback interfaces should be included.+func WithIncludeLoopback(include bool) includeLoopbackOption {+ return includeLoopbackOption(include)+}++func (o includeLoopbackOption) applyServer(c *serverConfig) error {+ c.includeLoopback = bool(o)++ return nil+}++func (o includeLoopbackOption) applyClient(c *clientConfig) error {+ c.includeLoopback = bool(o)++ return nil+}++// interfacesOption sets the interfaces to use.+type interfacesOption []net.Interface++// WithInterfaces sets the network interfaces to use.+// If not set, all suitable interfaces will be discovered automatically.+func WithInterfaces(ifaces ...net.Interface) interfacesOption {+ return interfacesOption(ifaces)+}++func (o interfacesOption) applyServer(c *serverConfig) error {+ c.interfaces = []net.Interface(o)++ return nil+}++func (o interfacesOption) applyClient(c *clientConfig) error {+ c.interfaces = []net.Interface(o)++ return nil+}++// Server-only options++// localNamesOption sets the local names to respond to.+type localNamesOption []string++// WithLocalNames sets the names that the server will respond to.+// These are the mDNS names that this server will generate answers for.+func WithLocalNames(names ...string) localNamesOption {+ return localNamesOption(names)+}++func (o localNamesOption) applyServer(c *serverConfig) error {+ c.localNames = []string(o)++ return nil+}++// localAddressOption sets the local address to publish.+type localAddressOption struct {+ addr net.IP+}++// WithLocalAddress sets the IP address to publish in responses.+// If not set, the address will be automatically determined from the interface.+func WithLocalAddress(addr net.IP) localAddressOption {+ return localAddressOption{addr: addr}+}++func (o localAddressOption) applyServer(c *serverConfig) error {+ c.localAddress = o.addr++ return nil+}++// recordTypesOption limits which record types are processed.+type recordTypesOption []dnsmessage.Type++// WithRecordTypes limits which DNS record types the server will process.+// By default (if not called), all record types are allowed - no filtering.+//+// For WebRTC/ICE usage (legacy behavior), restrict to address records:+//+// mdns.WithRecordTypes(dnsmessage.TypeA, dnsmessage.TypeAAAA)+func WithRecordTypes(types ...dnsmessage.Type) recordTypesOption {+ return recordTypesOption(types)+}++func (o recordTypesOption) applyServer(c *serverConfig) error {+ c.allowedRecordTypes = []dnsmessage.Type(o)++ return nil+}++// serviceOption registers a DNS-SD service instance to advertise.+type serviceOption struct {+ svc ServiceInstance+}++// WithService registers a DNS-SD service instance to be advertised.+// May be called multiple times to register multiple services.+//+// The Domain defaults to "local" if unset.+//+// Example:+//+// mdns.NewServer(v4, v6,+// mdns.WithLocalNames("myhost.local"),+// mdns.WithService(mdns.ServiceInstance{+// Instance: "My Web Server",+// Service: "_http._tcp",+// Port: 8080,+// }),+// )+func WithService(svc ServiceInstance) serviceOption {+ return serviceOption{svc: svc}+}++func (o serviceOption) applyServer(cfg *serverConfig) error {+ if err := validateInstanceName(o.svc.Instance); err != nil {+ return err+ }++ if err := validateServiceName(o.svc.Service); err != nil {+ return err+ }++ if err := validateTXTEntries(o.svc.Text); err != nil {+ return err+ }++ // Default domain to "local".+ if o.svc.Domain == "" {+ o.svc.Domain = "local"+ }++ cfg.services = append(cfg.services, o.svc)++ return nil+}++// responseTTLOption sets the TTL for DNS responses.+type responseTTLOption uint32++// WithResponseTTL sets the TTL (in seconds) for DNS response records.+// Default is 120 seconds per RFC 6762 recommendation.+func WithResponseTTL(seconds uint32) responseTTLOption {+ return responseTTLOption(seconds)+}++func (o responseTTLOption) applyServer(c *serverConfig) error {+ if o == 0 {+ return errResponseTTLZero+ }++ c.responseTTL = uint32(o)++ return nil+}++// cacheRefreshOption enables or disables proactive cache refresh.+type cacheRefreshOption bool++// WithCacheRefresh enables or disables proactive cache refresh per RFC 6762 §5.2.+// When enabled, actively-monitored records are re-queried at 80/85/90/95%+// of their TTL. Enabled by default in NewServer; disabled in the legacy+// Server constructor.+func WithCacheRefresh(enable bool) cacheRefreshOption {+ return cacheRefreshOption(enable)+}++func (o cacheRefreshOption) applyServer(c *serverConfig) error {+ c.cacheRefresh = bool(o)++ return nil+}++// refreshIntervalOption sets the refresh check interval.+type refreshIntervalOption time.Duration++// WithRefreshInterval sets how often the cache refresh loop checks for+// records due for refresh. Default is 2 seconds. Must be greater than+// zero. Only effective when cache refresh is enabled.+func WithRefreshInterval(interval time.Duration) refreshIntervalOption {+ return refreshIntervalOption(interval)+}++func (o refreshIntervalOption) applyServer(c *serverConfig) error {+ if o <= 0 {+ return errIntervalNonPositive+ }++ c.refreshCheckInterval = time.Duration(o)++ return nil+}++// queryIntervalOption sets the client query interval.+type queryIntervalOption time.Duration++// WithQueryInterval sets how often the client checks for records+// due for query. Default is 1 second. Must be greater than+// zero.+func WithQueryInterval(interval time.Duration) queryIntervalOption {+ return queryIntervalOption(interval)+}++func (o queryIntervalOption) applyServer(c *serverConfig) error {+ if o <= 0 {+ return errIntervalNonPositive+ }++ c.queryInterval = time.Duration(o)++ return nil+}++func (o queryIntervalOption) applyClient(c *clientConfig) error {+ if o <= 0 {+ return errIntervalNonPositive+ }++ c.queryInterval = time.Duration(o)++ return nil+}diff --git a/client-core/third_party/pion-mdns/conn.go b/client-core/third_party/pion-mdns/conn.gonew file mode 100644index 0000000..7bfbf98--- /dev/null+++ b/client-core/third_party/pion-mdns/conn.go@@ -0,0 +1,795 @@+// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "context"+ "errors"+ "fmt"+ "net"+ "net/netip"+ "sync"+ "sync/atomic"+ "time"++ "github.com/pion/logging"+ "golang.org/x/net/dns/dnsmessage"+)++// Conn represents a mDNS Server.+type Conn struct {+ mu sync.RWMutex+ name string+ log logging.LeveledLogger++ multicastPktConnV4 ipPacketConn+ multicastPktConnV6 ipPacketConn+ dstAddr4 *net.UDPAddr+ dstAddr6 *net.UDPAddr++ unicastPktConnV4 ipPacketConn+ unicastPktConnV6 ipPacketConn++ queryInterval time.Duration+ localNames []string+ ifaces map[int]netInterface++ // client handles query operations+ client *client+ // server handles response operations+ server *server++ // cache stores received DNS records with TTL management.+ cache *cache++ // stopBackground signals background goroutines (sweep, refresh) to stop.+ stopBackground chan struct{}++ // cacheRefresh enables proactive cache refresh per RFC 6762 §5.2.+ cacheRefresh bool++ // refreshCheckInterval overrides the default refresh polling interval.+ refreshCheckInterval time.Duration++ // sweepInterval overrides the default cache sweep interval.+ sweepInterval time.Duration++ // onServiceDiscovered is the handler for Browse results.+ onServiceDiscovered atomic.Value // func(ServiceEvent)++ // onServiceTypeDiscovered is the handler for EnumerateServiceTypes results.+ onServiceTypeDiscovered atomic.Value // func(string)++ closed chan any+}++type query struct {+ nameWithSuffix string+ queryResultChan chan queryResult+}++type queryResult struct {+ answer dnsmessage.ResourceHeader+ addr netip.Addr+}++const (+ defaultQueryInterval = time.Second+ defaultSweepInterval = 10 * time.Second+ defaultRefreshCheckInterval = 2 * time.Second+ destinationAddress4 = "224.0.0.251:5353"+ destinationAddress6 = "[FF02::FB]:5353"+ responseTTL = 120+ // maxPacketSize is the maximum size of a mdns packet.+ // From RFC 6762:+ // Even when fragmentation is used, a Multicast DNS packet, including IP+ // and UDP headers, MUST NOT exceed 9000 bytes.+ // https://datatracker.ietf.org/doc/html/rfc6762#section-17+ maxPacketSize = 9000+)++var (+ errNoPositiveMTUFound = errors.New("no positive MTU found")+ errNoPacketConn = errors.New("must supply at least a multicast IPv4 or IPv6 PacketConn")+ errNoUsableInterfaces = errors.New("no usable interfaces found for mDNS")+ errFailedToClose = errors.New("failed to close mDNS Conn")+)++type netInterface struct {+ net.Interface+ ipAddrs []netip.Addr+ supportsV4 bool+ supportsV6 bool+}++// Close closes the mDNS Conn.+func (c *Conn) Close() error { //nolint:cyclop+ select {+ case <-c.closed:+ return nil+ default:+ }++ // Once on go1.20, can use errors.Join+ var errs []error+ if c.multicastPktConnV4 != nil {+ if err := c.multicastPktConnV4.Close(); err != nil {+ errs = append(errs, err)+ }+ }++ if c.multicastPktConnV6 != nil {+ if err := c.multicastPktConnV6.Close(); err != nil {+ errs = append(errs, err)+ }+ }++ if c.unicastPktConnV4 != nil {+ if err := c.unicastPktConnV4.Close(); err != nil {+ errs = append(errs, err)+ }+ }++ if c.unicastPktConnV6 != nil {+ if err := c.unicastPktConnV6.Close(); err != nil {+ errs = append(errs, err)+ }+ }++ if len(errs) == 0 {+ <-c.closed++ return nil+ }++ rtrn := errFailedToClose+ for _, err := range errs {+ rtrn = fmt.Errorf("%w\n%w", err, rtrn)+ }++ return rtrn+}++// Register adds a DNS-SD service instance to the server.+// The service will be advertised in response to PTR, SRV, and TXT queries.+// Returns an error if the connection is closed or has no server.+func (c *Conn) Register(svc ServiceInstance) error {+ select {+ case <-c.closed:+ return errConnectionClosed+ default:+ }++ if c.server == nil {+ return errConnectionClosed+ }++ if err := validateInstanceName(svc.Instance); err != nil {+ return err+ }++ if err := validateServiceName(svc.Service); err != nil {+ return err+ }++ if svc.Domain == "" {+ svc.Domain = "local"+ }++ if svc.Host == "" && len(c.localNames) > 0 {+ svc.Host = c.localNames[0]+ }++ c.server.registerService(svc)++ return nil+}++// UpdateTXT replaces the TXT data of a registered DNS-SD service and+// immediately announces the new record. The instance is identified by its+// Instance name and Service type.+//+// https://www.rfc-editor.org/rfc/rfc6762.html#section-8.4+// https://www.rfc-editor.org/rfc/rfc6762.html#section-10.2+func (c *Conn) UpdateTXT(instance, service string, text []TXTEntry) error {+ select {+ case <-c.closed:+ return errConnectionClosed+ default:+ }++ if c.server == nil {+ return errConnectionClosed+ }++ if err := validateInstanceName(instance); err != nil {+ return err+ }+ if err := validateServiceName(service); err != nil {+ return err+ }+ if err := validateTXTEntries(text); err != nil {+ return err+ }++ generation, err := c.server.updateTXT(instance, service, text)+ if err != nil || generation == 0 {+ return err+ }++ go c.repeatTXTAnnouncement(instance, service, generation)++ return nil+}++func (c *Conn) repeatTXTAnnouncement(instance, service string, generation uint64) {+ timer := time.NewTimer(time.Second)+ defer timer.Stop()++ select {+ case <-timer.C:+ if err := c.server.repeatTXTAnnouncement(instance, service, generation); err != nil {+ c.log.Warnf("[%s] failed to repeat TXT announcement: %v", c.name, err)+ }+ case <-c.closed:+ }+}++// Unregister removes a DNS-SD service instance from the server.+// The instance is identified by its Instance name and Service type.+func (c *Conn) Unregister(instance, service string) {+ if c.server == nil {+ return+ }++ c.server.unregisterService(instance, service)+}++// OnServiceDiscovered sets a handler that is fired when a DNS-SD service+// instance is discovered during browsing. The handler is stored atomically+// and may be changed at any time. Set to nil to clear.+func (c *Conn) OnServiceDiscovered(handler func(ServiceEvent)) {+ c.onServiceDiscovered.Store(handler)+}++// serviceDiscoveredHandler dispatches a ServiceEvent to the registered handler.+func (c *Conn) serviceDiscoveredHandler(evt ServiceEvent) {+ if handler, ok := c.onServiceDiscovered.Load().(func(ServiceEvent)); ok && handler != nil {+ handler(evt)+ }+}++// OnServiceTypeDiscovered sets a handler that is fired when a service type+// is discovered during enumeration. The handler is stored atomically+// and may be changed at any time. Set to nil to clear.+func (c *Conn) OnServiceTypeDiscovered(handler func(string)) {+ c.onServiceTypeDiscovered.Store(handler)+}++// serviceTypeDiscoveredHandler dispatches a service type to the registered handler.+func (c *Conn) serviceTypeDiscoveredHandler(serviceType string) {+ if handler, ok := c.onServiceTypeDiscovered.Load().(func(string)); ok && handler != nil {+ handler(serviceType)+ }+}++// Browse starts discovering DNS-SD service instances of the given type on+// the local network. It sends periodic PTR queries for+// "<serviceType>.local." and fires the OnServiceDiscovered handler for each+// unique instance found.+//+// The context controls the lifetime of the browse operation.+// Discovered instances are deduplicated.+//+// Example:+//+// conn.OnServiceDiscovered(func(evt mdns.ServiceEvent) {+// fmt.Printf("Found: %s at %s:%d\n",+// evt.Instance.Instance, evt.Addr, evt.Instance.Port)+// })+// err := conn.Browse(ctx, "_http._tcp")+func (c *Conn) Browse(ctx context.Context, serviceType string) error {+ select {+ case <-c.closed:+ return errConnectionClosed+ default:+ }++ if c.client == nil {+ return errConnectionClosed+ }++ if err := validateServiceName(serviceType); err != nil {+ return err+ }++ session := newBrowseSession(ctx, serviceType, c.serviceDiscoveredHandler)++ c.client.handler.registerBrowseSession(session)++ go c.browseLoop(session)++ return nil+}++// browseLoop sends periodic PTR queries until the context is done.+func (c *Conn) browseLoop(session *browseSession) {+ defer func() {+ c.client.handler.unregisterBrowseSession(session)+ session.cancel()+ }()++ svcName := session.serviceName()+ c.client.sendBrowseQuestion(svcName)++ interval := c.queryInterval+ if interval == 0 {+ interval = defaultQueryInterval+ }+ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ c.client.sendBrowseQuestion(svcName)+ case <-session.done:+ return+ case <-c.closed:+ return+ }+ }+}++// EnumerateServiceTypes starts discovering all service types advertised on the+// local network using the DNS-SD service type enumeration meta-query+// (RFC 6763 §9).+//+// Fires the OnServiceTypeDiscovered handler for each unique service type found.+// The context controls the lifetime of the enumeration.+func (c *Conn) EnumerateServiceTypes(ctx context.Context) error {+ select {+ case <-c.closed:+ return errConnectionClosed+ default:+ }++ if c.client == nil {+ return errConnectionClosed+ }++ session := newEnumerateSession(ctx, c.serviceTypeDiscoveredHandler)++ c.client.handler.registerEnumerateSession(session)++ go c.enumerateLoop(session)++ return nil+}++// enumerateLoop sends periodic meta-queries until the context is done.+func (c *Conn) enumerateLoop(session *enumerateSession) {+ defer func() {+ c.client.handler.unregisterEnumerateSession(session)+ session.cancel()+ }()++ c.client.sendEnumerateQuestion(session.domain)++ interval := c.queryInterval+ if interval == 0 {+ interval = defaultQueryInterval+ }+ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ c.client.sendEnumerateQuestion(session.domain)+ case <-session.done:+ return+ case <-c.closed:+ return+ }+ }+}++// Query sends mDNS Queries for the following name until+// either the Context is canceled/expires or we get a result+//+// Deprecated: Use QueryAddr instead as it supports the easier to use netip.Addr.+func (c *Conn) Query(ctx context.Context, name string) (dnsmessage.ResourceHeader, net.Addr, error) {+ header, addr, err := c.QueryAddr(ctx, name)+ if err != nil {+ return header, nil, err+ }++ return header, &net.IPAddr{+ IP: addr.AsSlice(),+ Zone: addr.Zone(),+ }, nil+}++// QueryAddr sends mDNS Queries for the following name until+// either the Context is canceled/expires or we get a result.+func (c *Conn) QueryAddr(ctx context.Context, name string) (dnsmessage.ResourceHeader, netip.Addr, error) {+ select {+ case <-c.closed:+ return dnsmessage.ResourceHeader{}, netip.Addr{}, errConnectionClosed+ default:+ }++ if c.client == nil {+ return dnsmessage.ResourceHeader{}, netip.Addr{}, errConnectionClosed+ }++ nameWithSuffix := name + "."+ queryChan := make(chan queryResult, 1)+ q := c.client.handler.registerQuery(nameWithSuffix, queryChan)+ defer c.client.handler.unregisterQuery(q)++ interval := c.queryInterval+ if interval == 0 {+ interval = defaultQueryInterval+ }+ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ c.client.sendQuestion(nameWithSuffix)+ for {+ select {+ case <-ticker.C:+ c.client.sendQuestion(nameWithSuffix)+ case <-c.closed:+ return dnsmessage.ResourceHeader{}, netip.Addr{}, errConnectionClosed+ case res := <-queryChan:+ // Given https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-mdns-ice-candidates#section-3.2.2-2+ // An ICE agent SHOULD ignore candidates where the hostname resolution returns more than one IP address.+ //+ // We will take the first we receive which could result in a race between two suitable addresses where+ // one is better than the other (e.g. localhost vs LAN).+ return res.answer, res.addr, nil+ case <-ctx.Done():+ return dnsmessage.ResourceHeader{}, netip.Addr{}, errContextElapsed+ }+ }+}++// writeQuestion sends a DNS question to all interfaces.+// It prefers unicast connections if available, falling back to multicast.+//+//nolint:gocognit,cyclop,nestif+func (c *Conn) writeQuestion(b []byte) {+ for ifcIdx := range c.ifaces {+ ifc := c.ifaces[ifcIdx]++ // We'll write via unicast if we can in case the responder chooses to respond to the address+ // the request came from (i.e. not respecting unicast-response bit). If we were to use the+ // multicast packet conn here, we'd be writing from a specific multicast address which won't+ // be able to receive unicast traffic (it only works when listening on 0.0.0.0/[::]).+ if c.unicastPktConnV4 == nil && c.unicastPktConnV6 == nil {+ c.log.Debugf("[%s] writing question to multicast IPv4/6 %s", c.name, c.dstAddr4)+ if ifc.supportsV4 && c.multicastPktConnV4 != nil {+ if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, c.dstAddr4); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv4 interface %d: %v", c.name, ifc.Index, err)+ }+ }+ if ifc.supportsV6 && c.multicastPktConnV6 != nil {+ if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, c.dstAddr6); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv6 interface %d: %v", c.name, ifc.Index, err)+ }+ }+ }+ if ifc.supportsV4 && c.unicastPktConnV4 != nil {+ c.log.Debugf("[%s] writing question to unicast IPv4 %s", c.name, c.dstAddr4)+ if _, err := c.unicastPktConnV4.WriteTo(b, &ifc.Interface, nil, c.dstAddr4); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (unicast) on interface %d: %v", c.name, ifc.Index, err)+ }+ }+ if ifc.supportsV6 && c.unicastPktConnV6 != nil {+ c.log.Debugf("[%s] writing question to unicast IPv6 %s", c.name, c.dstAddr6)+ if _, err := c.unicastPktConnV6.WriteTo(b, &ifc.Interface, nil, c.dstAddr6); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (unicast) on interface %d: %v", c.name, ifc.Index, err)+ }+ }+ }+}++// writeAnswer sends a DNS answer, optionally to a specific interface or unicast destination.+//+//nolint:gocognit,gocyclo,cyclop+func (c *Conn) writeAnswer(+ ifIndex int,+ b []byte,+ hasLoopbackData bool,+ hasIPv6Zone bool,+ unicastDst *net.UDPAddr,+) {+ var dst4, dst6 net.Addr+ if unicastDst == nil {+ dst4 = c.dstAddr4+ dst6 = c.dstAddr6+ } else {+ if unicastDst.IP.To4() == nil {+ dst6 = unicastDst+ } else {+ dst4 = unicastDst+ }+ }++ if ifIndex != -1 { //nolint:nestif+ ifc, ok := c.ifaces[ifIndex]+ if !ok {+ c.log.Warnf("[%s] no interface for %d", c.name, ifIndex)++ return+ }+ if hasLoopbackData && ifc.Flags&net.FlagLoopback == 0 {+ // avoid accidentally tricking the destination that itself is the same as us+ c.log.Debugf("[%s] interface is not loopback %d", c.name, ifIndex)++ return+ }++ c.log.Debugf("[%s] writing answer to IPv4: %v, IPv6: %v", c.name, dst4, dst6)++ if ifc.supportsV4 && c.multicastPktConnV4 != nil && dst4 != nil {+ if !hasIPv6Zone {+ if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, dst4); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet on IPv4 interface %d: %v", c.name, ifIndex, err)+ }+ } else {+ c.log.Debugf("[%s] refusing to send mDNS packet with IPv6 zone over IPv4", c.name)+ }+ }+ if ifc.supportsV6 && c.multicastPktConnV6 != nil && dst6 != nil {+ if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, dst6); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet on IPv6 interface %d: %v", c.name, ifIndex, err)+ }+ }++ return+ }++ for ifcIdx := range c.ifaces {+ ifc := c.ifaces[ifcIdx]+ if hasLoopbackData {+ c.log.Debugf("[%s] Refusing to send loopback data with non-specific interface", c.name)++ continue+ }++ c.log.Debugf("[%s] writing answer to IPv4: %v, IPv6: %v", c.name, dst4, dst6)++ if ifc.supportsV4 && c.multicastPktConnV4 != nil && dst4 != nil {+ if !hasIPv6Zone {+ if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, dst4); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv4 interface %d: %v", c.name, ifIndex, err)+ }+ } else {+ c.log.Debugf("[%s] refusing to send mDNS packet with IPv6 zone over IPv4", c.name)+ }+ }+ if ifc.supportsV6 && c.multicastPktConnV6 != nil && dst6 != nil {+ if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, dst6); err != nil {+ c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv6 interface %d: %v", c.name, ifIndex, err)+ }+ }+ }+}++func (c *Conn) readLoop(name string, pktConn ipPacketConn, inboundBufferSize int, _ *serverConfig) {+ b := make([]byte, inboundBufferSize)++ for {+ n, cm, src, err := pktConn.ReadFrom(b)+ if err != nil {+ if errors.Is(err, net.ErrClosed) {+ return+ }+ c.log.Warnf("[%s] failed to ReadFrom %q %v", c.name, src, err)++ continue+ }+ c.log.Debugf("[%s] got read on %s from %s", c.name, name, src)++ var ifIndex int+ var pktDst net.IP+ if cm != nil {+ ifIndex = cm.IfIndex+ pktDst = cm.Dst+ } else {+ ifIndex = -1+ }+ srcAddr, ok := src.(*net.UDPAddr)+ if !ok {+ c.log.Warnf("[%s] expected source address %s to be UDP but got %", c.name, src, src)++ continue+ }++ func() {+ var msg dnsmessage.Message+ err := msg.Unpack(b[:n])+ if err != nil {+ c.log.Warnf("[%s] failed to parse mDNS packet %v", c.name, err)++ return+ }++ ctx := &messageContext{+ source: srcAddr,+ ifIndex: ifIndex,+ pktDst: pktDst,+ timestamp: time.Now(),+ }++ // Questions are often echoed with answers, therefore+ // If we have more questions than answers it is a question we might need to respond to+ if len(msg.Questions) > len(msg.Answers) {+ if c.server != nil {+ c.server.handler.handle(ctx, &msg)+ }+ } else {+ if c.client != nil {+ c.client.handler.handle(ctx, &msg)+ }+ }+ }()+ }+}++func (c *Conn) start(started chan<- struct{}, inboundBufferSize int, config *serverConfig) {+ defer func() {+ c.mu.Lock()+ defer c.mu.Unlock()+ close(c.closed)+ }()++ backgroundWG := c.startBackgroundLoops()++ var numReaders int+ readerStarted := make(chan struct{})+ readerEnded := make(chan struct{})++ if c.multicastPktConnV4 != nil {+ numReaders+++ go func() {+ defer func() {+ readerEnded <- struct{}{}+ }()+ readerStarted <- struct{}{}+ c.readLoop("multi4", c.multicastPktConnV4, inboundBufferSize, config)+ }()+ }+ if c.multicastPktConnV6 != nil {+ numReaders+++ go func() {+ defer func() {+ readerEnded <- struct{}{}+ }()+ readerStarted <- struct{}{}+ c.readLoop("multi6", c.multicastPktConnV6, inboundBufferSize, config)+ }()+ }+ if c.unicastPktConnV4 != nil {+ numReaders+++ go func() {+ defer func() {+ readerEnded <- struct{}{}+ }()+ readerStarted <- struct{}{}+ c.readLoop("uni4", c.unicastPktConnV4, inboundBufferSize, config)+ }()+ }+ if c.unicastPktConnV6 != nil {+ numReaders+++ go func() {+ defer func() {+ readerEnded <- struct{}{}+ }()+ readerStarted <- struct{}{}+ c.readLoop("uni6", c.unicastPktConnV6, inboundBufferSize, config)+ }()+ }+ for i := 0; i < numReaders; i++ {+ <-readerStarted+ }+ close(started)+ for i := 0; i < numReaders; i++ {+ <-readerEnded+ }++ // All readers done — stop background goroutines.+ if c.stopBackground != nil {+ close(c.stopBackground)+ }++ backgroundWG.Wait()+}++// startBackgroundLoops launches the sweep and optional refresh goroutines.+// Returns a WaitGroup that completes when all background goroutines exit.+func (c *Conn) startBackgroundLoops() *sync.WaitGroup {+ var backgroundWG sync.WaitGroup++ if c.cache == nil || c.stopBackground == nil {+ return &backgroundWG+ }++ backgroundWG.Add(1)++ go func() {+ defer backgroundWG.Done()+ c.sweepLoop()+ }()++ if c.cacheRefresh {+ backgroundWG.Add(1)++ go func() {+ defer backgroundWG.Done()+ c.refreshLoop()+ }()+ }++ return &backgroundWG+}++// sweepLoop periodically removes expired cache entries.+func (c *Conn) sweepLoop() {+ interval := c.sweepInterval+ if interval == 0 {+ interval = defaultSweepInterval+ }++ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ c.cache.sweep()+ case <-c.stopBackground:+ return+ }+ }+}++// refreshLoop periodically checks monitored cache entries for refresh.+// Per RFC 6762 §5.2, actively-monitored records are refreshed at+// 80/85/90/95% of their TTL.+func (c *Conn) refreshLoop() {+ interval := c.refreshCheckInterval+ if interval == 0 {+ interval = defaultRefreshCheckInterval+ }++ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ticker.C:+ keys := c.client.handler.monitoredCacheKeys()+ if candidates := c.cache.takeRefreshCandidates(keys); len(candidates) > 0 {+ c.client.sendRefreshQuestions(candidates)+ }+ case <-c.stopBackground:+ return+ }+ }+}++func addrWithOptionalZone(addr netip.Addr, zone string) netip.Addr {+ if zone == "" {+ return addr+ }+ if addr.Is6() && (addr.IsLinkLocalUnicast() || addr.IsLinkLocalMulticast()) {+ return addr.WithZone(zone)+ }++ return addr+}diff --git a/client-core/third_party/pion-mdns/dns_sd.go b/client-core/third_party/pion-mdns/dns_sd.gonew file mode 100644index 0000000..ce20bd4--- /dev/null+++ b/client-core/third_party/pion-mdns/dns_sd.go@@ -0,0 +1,371 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "errors"+ "net/netip"+ "strings"+ "unicode/utf8"+)++// serviceTypeEnumerationName is the meta-query name for discovering all+// service types on the network (RFC 6763 §9).+// A PTR query for "_services._dns-sd._udp.<Domain>" yields PTR records+// whose rdata is the two-label <Service> name plus the domain.+const serviceTypeEnumerationName = "_services._dns-sd._udp"++// maxInstanceNameLen is the maximum length of a DNS label (RFC 1035 §2.3.4),+// which constrains the Instance portion of a Service Instance Name.+const maxInstanceNameLen = 63++var (+ errInvalidServiceName = errors.New("mDNS: invalid DNS-SD service name")+ errInstanceNameTooLong = errors.New("mDNS: service instance name exceeds 63 bytes")+ errInstanceNameEmpty = errors.New("mDNS: service instance name must not be empty")+ errInstanceNameHasControl = errors.New("mDNS: service instance name contains ASCII control character")+ errUnhandledServiceQuestionType = errors.New("mDNS: unhandled DNS-SD question type")+)++// ServiceEventType identifies why a ServiceEvent was emitted.+type ServiceEventType uint8++const (+ // ServiceAdded indicates that a service instance was resolved for the first time.+ ServiceAdded ServiceEventType = iota+ // ServiceUpdated indicates that a resolved service instance changed while+ // it was being continuously monitored.+ //+ // https://www.rfc-editor.org/rfc/rfc6762.html#section-5.2+ ServiceUpdated+)++// ServiceEvent represents a resolved DNS-SD service instance.+// It is emitted by Browse when a complete service instance has been resolved+// (PTR → SRV + TXT → address).+type ServiceEvent struct {+ // Type identifies whether the service was added or updated.+ Type ServiceEventType++ // Instance is the discovered service.+ Instance ServiceInstance++ // Addr is the resolved address of the service host.+ Addr netip.Addr+}++// ServiceInstance represents a DNS-SD service instance (RFC 6763).+//+// A service instance is identified by:+//+// <Instance>.<Service>.<Domain>+//+// Example:+//+// Instance: "My Web Server"+// Service: "_http._tcp"+// Domain: "local"+// Host: "myhost.local."+// Port: 8080+type ServiceInstance struct {+ // Instance is the user-friendly name (UTF-8, max 63 bytes after encoding).+ // May contain dots and other punctuation (RFC 6763 §4.1.1).+ Instance string++ // Service is the service type, e.g. "_http._tcp".+ // Must be in the form "_<name>._<proto>" where proto is "tcp" or "udp".+ Service string++ // Domain is the DNS domain, typically "local" for mDNS.+ Domain string++ // Host is the target hostname for the SRV record (e.g. "myhost.local.").+ Host string++ // Port is the TCP or UDP port number.+ Port uint16++ // Priority is the SRV priority field (lower = preferred). Default 0.+ Priority uint16++ // Weight is the SRV weight field. Default 0.+ Weight uint16++ // Text contains the key/value pairs for the TXT record.+ Text []TXTEntry+}++// serviceInstanceName returns the fully-qualified DNS name for this instance.+// Dots and backslashes in the Instance portion are escaped per RFC 6763 §4.3:+// - Literal dots become "\."+// - Literal backslashes become "\\"+//+// Example:+//+// Instance="My.Web", Service="_http._tcp", Domain="local"+// → "My\.Web._http._tcp.local."+func (si *ServiceInstance) serviceInstanceName() string {+ escaped := escapeInstanceName(si.Instance)++ return escaped + "." + si.Service + "." + si.Domain + "."+}++// serviceName returns the <Service>.<Domain> browsing name+// (e.g. "_http._tcp.local.").+func (si *ServiceInstance) serviceName() string {+ return si.Service + "." + si.Domain + "."+}++// escapeInstanceName escapes dots and backslashes in an instance name+// for safe concatenation into a DNS name string (RFC 6763 §4.3).+func escapeInstanceName(instance string) string {+ // Fast path: no escaping needed+ if !strings.ContainsAny(instance, `.\`) {+ return instance+ }++ var buf strings.Builder+ buf.Grow(len(instance) + 4) // room for a few escapes+ for _, c := range instance {+ switch c {+ case '.':+ buf.WriteString(`\.`)+ case '\\':+ buf.WriteString(`\\`)+ default:+ buf.WriteRune(c)+ }+ }++ return buf.String()+}++// unescapeInstanceName reverses the escaping applied by escapeInstanceName.+// It converts "\." back to "." and "\\" back to "\".+func unescapeInstanceName(escaped string) string {+ if !strings.ContainsRune(escaped, '\\') {+ return escaped+ }++ var b strings.Builder+ b.Grow(len(escaped))+ for i := 0; i < len(escaped); i++ {+ switch {+ case escaped[i] == '\\' && i+1 < len(escaped):+ i+++ b.WriteByte(escaped[i])+ default:+ b.WriteByte(escaped[i])+ }+ }++ return b.String()+}++// parseServiceInstanceName splits a fully-qualified DNS name into its+// Instance, Service, and Domain components.+//+// The expected format is:+//+// <Instance>.<_name>.<_proto>.<Domain>.+//+// Dots within the Instance portion must be escaped as "\." (RFC 6763 §4.3).+// The trailing dot is optional.+//+// Examples:+//+// "My Web._http._tcp.local." → ("My Web", "_http._tcp", "local")+// "My\.Web._http._tcp.local." → ("My.Web", "_http._tcp", "local")+func parseServiceInstanceName(name string) (instance, service, domain string, err error) {+ // Strip trailing dot+ name = strings.TrimSuffix(name, ".")++ // Split on unescaped dots. We need at least 4 labels:+ // <instance>, <_name>, <_proto>, <domain...>+ labels := splitEscapedDots(name)+ if len(labels) < 4 {+ return "", "", "", errInvalidServiceName+ }++ // The service is always the two labels starting with underscore.+ // Walk from position 1 to find _name._proto pattern.+ // The instance is everything before it, the domain is everything after.+ serviceIdx := -1+ for i := 1; i < len(labels)-1; i++ {+ if strings.HasPrefix(labels[i], "_") && strings.HasPrefix(labels[i+1], "_") {+ serviceIdx = i++ break+ }+ }+ if serviceIdx < 1 || serviceIdx+2 > len(labels) {+ return "", "", "", errInvalidServiceName+ }++ // Instance: rejoin labels before serviceIdx (unescaped)+ instanceParts := labels[:serviceIdx]+ instance = unescapeInstanceName(strings.Join(instanceParts, "."))++ service = labels[serviceIdx] + "." + labels[serviceIdx+1]+ domain = strings.Join(labels[serviceIdx+2:], ".")++ if instance == "" || service == "" || domain == "" {+ return "", "", "", errInvalidServiceName+ }++ return instance, service, domain, nil+}++// splitEscapedDots splits a string on dots that are NOT preceded by a backslash.+func splitEscapedDots(input string) []string {+ var labels []string+ var current strings.Builder++ for i := 0; i < len(input); i++ {+ switch {+ case input[i] == '\\' && i+1 < len(input):+ // Escaped character: keep both the backslash and the next char+ current.WriteByte(input[i])+ i+++ current.WriteByte(input[i])+ case input[i] == '.':+ labels = append(labels, current.String())+ current.Reset()+ default:+ current.WriteByte(input[i])+ }+ }+ labels = append(labels, current.String())++ return labels+}++// validateServiceName checks that a service string like "_http._tcp" follows+// the DNS-SD service naming rules (RFC 6763 §7, RFC 6335):+// - Format: "_<name>._<proto>"+// - Proto must be "_tcp" or "_udp"+// - Name: 1-15 characters (not counting underscore prefix)+// - Name: letters, digits, hyphens only+// - Name: must begin and end with a letter or digit+// - Name: must not contain consecutive hyphens+// - Name: must contain at least one letter+func validateServiceName(service string) error {+ parts := strings.SplitN(service, ".", 2)+ if len(parts) != 2 {+ return errInvalidServiceName+ }++ namePart := parts[0] // e.g. "_http"+ protoPart := parts[1] // e.g. "_tcp"++ if err := validateServiceProto(protoPart); err != nil {+ return err+ }++ return validateServiceLabel(namePart)+}++// validateServiceProto checks that the protocol label is "_tcp" or "_udp".+func validateServiceProto(proto string) error {+ if proto != "_tcp" && proto != "_udp" {+ return errInvalidServiceName+ }++ return nil+}++// validateServiceLabel checks the "_<name>" portion of a service name.+func validateServiceLabel(label string) error {+ if !strings.HasPrefix(label, "_") {+ return errInvalidServiceName+ }++ name := label[1:] // strip underscore prefix++ if len(name) == 0 || len(name) > 15 {+ return errInvalidServiceName+ }++ // Must begin and end with letter or digit+ if !isLetterOrDigit(name[0]) || !isLetterOrDigit(name[len(name)-1]) {+ return errInvalidServiceName+ }++ if err := validateServiceNameChars(name); err != nil {+ return err+ }++ return nil+}++// validateServiceNameChars checks individual characters in a service name:+// letters, digits, hyphens only; no consecutive hyphens; at least one letter.+func validateServiceNameChars(name string) error {+ hasLetter := false+ prevHyphen := false++ for i := 0; i < len(name); i++ {+ c := name[i]+ switch {+ case isLetter(c):+ hasLetter = true+ prevHyphen = false+ case isDigit(c):+ prevHyphen = false+ case c == '-':+ if prevHyphen {+ return errInvalidServiceName // consecutive hyphens+ }+ prevHyphen = true+ default:+ return errInvalidServiceName // invalid character+ }+ }++ if !hasLetter {+ return errInvalidServiceName+ }++ return nil+}++// validateInstanceName checks that an instance name is valid per RFC 6763 §4.1.1:+// - Must not be empty+// - Must not exceed 63 bytes when UTF-8 encoded+// - Must not contain ASCII control characters (0x00-0x1F, 0x7F)+func validateInstanceName(instance string) error {+ if instance == "" {+ return errInstanceNameEmpty+ }++ if len(instance) > maxInstanceNameLen {+ return errInstanceNameTooLong+ }++ for i := 0; i < len(instance); i++ {+ b := instance[i]+ if b <= 0x1F || b == 0x7F {+ return errInstanceNameHasControl+ }+ }++ // Verify valid UTF-8+ if !utf8.ValidString(instance) {+ return errInstanceNameHasControl+ }++ return nil+}++func isLetter(c byte) bool {+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')+}++func isDigit(c byte) bool {+ return c >= '0' && c <= '9'+}++func isLetterOrDigit(c byte) bool {+ return isLetter(c) || isDigit(c)+}diff --git a/client-core/third_party/pion-mdns/errors.go b/client-core/third_party/pion-mdns/errors.gonew file mode 100644index 0000000..dbc817e--- /dev/null+++ b/client-core/third_party/pion-mdns/errors.go@@ -0,0 +1,15 @@+// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import "errors"++var (+ errJoiningMulticastGroup = errors.New("mDNS: failed to join multicast group")+ errConnectionClosed = errors.New("mDNS: connection is closed")+ errContextElapsed = errors.New("mDNS: context has elapsed")+ errServiceNotFound = errors.New("mDNS: service is not registered")+ errNilConfig = errors.New("mDNS: config must not be nil")+ errFailedCast = errors.New("mDNS: failed to cast listener to UDPAddr")+)diff --git a/client-core/third_party/pion-mdns/go.mod b/client-core/third_party/pion-mdns/go.modnew file mode 100644index 0000000..1d54aae--- /dev/null+++ b/client-core/third_party/pion-mdns/go.mod@@ -0,0 +1,16 @@+module github.com/pion/mdns/v2++go 1.24.0++require (+ github.com/pion/logging v0.2.4+ github.com/pion/transport/v5 v5.0.0+ github.com/stretchr/testify v1.12.1+ golang.org/x/net v0.35.0+)++require (+ github.com/wlynxg/anet v0.0.5+ go.yaml.in/yaml/v3 v3.0.5 // indirect+ golang.org/x/sys v0.41.0 // indirect+)diff --git a/client-core/third_party/pion-mdns/go.sum b/client-core/third_party/pion-mdns/go.sumnew file mode 100644index 0000000..f15bcb6--- /dev/null+++ b/client-core/third_party/pion-mdns/go.sum@@ -0,0 +1,12 @@+github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=+github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=+github.com/pion/transport/v5 v5.0.0 h1:XWdfCnG6oLaTp07Sr4lbyWVs+MXuaD3eggUsSn6LK90=+github.com/pion/transport/v5 v5.0.0/go.mod h1:Qxw6fCEjFWQkRDZOhS4Vf+neJBcihauvA3uyEa1J1F0=+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=+golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=+golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=+golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=diff --git a/client-core/third_party/pion-mdns/mdns.go b/client-core/third_party/pion-mdns/mdns.gonew file mode 100644index 0000000..7b56686--- /dev/null+++ b/client-core/third_party/pion-mdns/mdns.go@@ -0,0 +1,5 @@+// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++// Package mdns implements mDNS (multicast DNS)+package mdnsdiff --git a/client-core/third_party/pion-mdns/networking.go b/client-core/third_party/pion-mdns/networking.gonew file mode 100644index 0000000..713e26a--- /dev/null+++ b/client-core/third_party/pion-mdns/networking.go@@ -0,0 +1,179 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "fmt"+ "net"+ "net/netip"++ "github.com/pion/logging"+ "golang.org/x/net/ipv4"+ "golang.org/x/net/ipv6"+)++type ipToAddrError struct {+ ip []byte+}++func (err ipToAddrError) Error() string {+ return fmt.Sprintf("failed to convert ip address '%s' to netip.Addr", err.ip)+}++func interfaceForRemote(remote string) (*netip.Addr, error) {+ conn, err := net.Dial("udp", remote) //nolint: noctx+ if err != nil {+ return nil, err+ }++ localAddr, ok := conn.LocalAddr().(*net.UDPAddr)+ if !ok {+ return nil, errFailedCast+ }++ if err := conn.Close(); err != nil {+ return nil, err+ }++ ipAddr, ok := netip.AddrFromSlice(localAddr.IP)+ if !ok {+ return nil, ipToAddrError{localAddr.IP}+ }+ ipAddr = addrWithOptionalZone(ipAddr, localAddr.Zone)++ return &ipAddr, nil+}++type ipControlMessage struct {+ IfIndex int+ Dst net.IP+}++type ipPacketConn interface {+ ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error)+ WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error)+ Close() error+}++type ipPacketConn4 struct {+ name string+ conn *ipv4.PacketConn+ log logging.LeveledLogger+}++func (c ipPacketConn4) ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error) {+ n, cm4, src, err := c.conn.ReadFrom(b)+ if err != nil || cm4 == nil {+ return n, nil, src, err+ }++ return n, &ipControlMessage{IfIndex: cm4.IfIndex, Dst: cm4.Dst}, src, err+}++func (c ipPacketConn4) WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error) {+ var cm4 *ipv4.ControlMessage+ if cm != nil {+ cm4 = &ipv4.ControlMessage{+ IfIndex: cm.IfIndex,+ }+ }+ if err := c.conn.SetMulticastInterface(via); err != nil {+ c.log.Warnf("[%s] failed to set multicast interface for %d: %v", c.name, via.Index, err)++ return 0, err+ }++ return c.conn.WriteTo(b, cm4, dst)+}++func (c ipPacketConn4) Close() error {+ return c.conn.Close()+}++type ipPacketConn6 struct {+ name string+ conn *ipv6.PacketConn+ log logging.LeveledLogger+}++func (c ipPacketConn6) ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error) {+ n, cm6, src, err := c.conn.ReadFrom(b)+ if err != nil || cm6 == nil {+ return n, nil, src, err+ }++ return n, &ipControlMessage{IfIndex: cm6.IfIndex, Dst: cm6.Dst}, src, err+}++func (c ipPacketConn6) WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error) {+ var cm6 *ipv6.ControlMessage+ if cm != nil {+ cm6 = &ipv6.ControlMessage{+ IfIndex: cm.IfIndex,+ }+ }+ if err := c.conn.SetMulticastInterface(via); err != nil {+ c.log.Warnf("[%s] failed to set multicast interface for %d: %v", c.name, via.Index, err)++ return 0, err+ }++ return c.conn.WriteTo(b, cm6, dst)+}++func (c ipPacketConn6) Close() error {+ return c.conn.Close()+}++// configurePacketConn4 sets up control messages on an IPv4 PacketConn and returns the wrapper.+// Returns nil if pc is nil.+func configurePacketConn4(pc *ipv4.PacketConn, name, connType string, log logging.LeveledLogger) ipPacketConn {+ if pc == nil {+ return nil+ }+ if err := pc.SetControlMessage(ipv4.FlagInterface, true); err != nil {+ log.Warnf("[%s] failed to SetControlMessage(FlagInterface) on %s IPv4 PacketConn: %v", name, connType, err)+ }+ if err := pc.SetControlMessage(ipv4.FlagDst, true); err != nil {+ log.Warnf("[%s] failed to SetControlMessage(FlagDst) on %s IPv4 PacketConn: %v", name, connType, err)+ }++ return ipPacketConn4{name, pc, log}+}++// configurePacketConn6 sets up control messages on an IPv6 PacketConn and returns the wrapper.+// Returns nil if pc is nil.+func configurePacketConn6(pc *ipv6.PacketConn, name, connType string, log logging.LeveledLogger) ipPacketConn {+ if pc == nil {+ return nil+ }+ if err := pc.SetControlMessage(ipv6.FlagInterface, true); err != nil {+ log.Warnf("[%s] failed to SetControlMessage(FlagInterface) on %s IPv6 PacketConn: %v", name, connType, err)+ }+ if err := pc.SetControlMessage(ipv6.FlagDst, true); err != nil {+ log.Warnf("[%s] failed to SetControlMessage(FlagDst) on %s IPv6 PacketConn: %v", name, connType, err)+ }++ return ipPacketConn6{name, pc, log}+}++// enableLoopback4 enables multicast loopback on an IPv4 PacketConn if non-nil.+func enableLoopback4(pc *ipv4.PacketConn, name, connType string, log logging.LeveledLogger) {+ if pc == nil {+ return+ }+ if err := pc.SetMulticastLoopback(true); err != nil {+ log.Warnf("[%s] failed to SetMulticastLoopback on %s IPv4 PacketConn: %v", name, connType, err)+ }+}++// enableLoopback6 enables multicast loopback on an IPv6 PacketConn if non-nil.+func enableLoopback6(pc *ipv6.PacketConn, name, connType string, log logging.LeveledLogger) {+ if pc == nil {+ return+ }+ if err := pc.SetMulticastLoopback(true); err != nil {+ log.Warnf("[%s] failed to SetMulticastLoopback on %s IPv6 PacketConn: %v", name, connType, err)+ }+}diff --git a/client-core/third_party/pion-mdns/records.go b/client-core/third_party/pion-mdns/records.gonew file mode 100644index 0000000..32052aa--- /dev/null+++ b/client-core/third_party/pion-mdns/records.go@@ -0,0 +1,389 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "bytes"+ "errors"+ "net/netip"+ "strings"++ "golang.org/x/net/dns/dnsmessage"+)++func cloneTXTEntries(entries []TXTEntry) []TXTEntry {+ cloned := make([]TXTEntry, len(entries))+ for i := range entries {+ cloned[i] = TXTEntry{Key: entries[i].Key, Value: bytes.Clone(entries[i].Value)}+ }++ return cloned+}++func txtEntriesEqual(a, b []TXTEntry) bool {+ if len(a) != len(b) {+ return false+ }++ for i := range a {+ if a[i].Key != b[i].Key || !bytes.Equal(a[i].Value, b[i].Value) {+ return false+ }+ }++ return true+}++// browseTTL is the recommended TTL for non-host-scoped records (browsing PTR,+// TXT) per RFC 6762 §10: 75 minutes = 4500 seconds.+const browseTTL uint32 = 4500++// maxTXTStringLen is the maximum length of a single constituent string within+// a DNS TXT record (RFC 1035 §3.3.14: 1-byte length prefix → max 255 bytes).+const maxTXTStringLen = 255++var (+ errTXTStringTooLong = errors.New("mDNS: TXT record string exceeds 255 bytes")+ errTXTKeyEmpty = errors.New("mDNS: TXT record key must not be empty")+ errTXTKeyHasEquals = errors.New("mDNS: TXT record key must not contain '='")+ errTXTKeyNotASCII = errors.New("mDNS: TXT record key must be printable US-ASCII (0x20-0x7E)")+ errTXTDuplicateKey = errors.New("mDNS: TXT record keys must be unique (case-insensitive)")+ errNotPTRResource = errors.New("mDNS: resource body is not PTR")+ errNotSRVResource = errors.New("mDNS: resource body is not SRV")+ errNotTXTResource = errors.New("mDNS: resource body is not TXT")+)++// TXTEntry represents a single key=value pair in a DNS-SD TXT record+// (RFC 6763 §6). Key is case-insensitive, printable US-ASCII (0x20-0x7E)+// excluding '=' (0x3D). Value is opaque bytes (often UTF-8).+//+// A nil Value indicates a boolean attribute — the key is simply present+// with no value. An empty (non-nil, zero-length) Value represents a key+// with an explicitly empty value (e.g. "PlugIns=").+//+// Prefer the NewTXTString, NewTXTBinary, and NewTXTFlag constructors over a+// struct literal: they map the three RFC 6763 §6.4 cases to distinct calls+// and avoid the nil-vs-empty Value footgun.+type TXTEntry struct {+ Key string+ Value []byte // nil = boolean attribute (present, no value)+}++// NewTXTString creates a TXT entry with a key and string value, encoded on+// the wire as "key=value". An empty value yields "key=" (RFC 6763 §6.4).+func NewTXTString(key, value string) TXTEntry {+ return TXTEntry{Key: key, Value: []byte(value)}+}++// NewTXTBinary creates a TXT entry with a key and an opaque binary value+// (RFC 6763 §6.5), encoded on the wire as "key=<bytes>". A nil value is+// treated as an explicit empty value ("key="); use NewTXTFlag for a boolean+// attribute that carries no value at all.+func NewTXTBinary(key string, value []byte) TXTEntry {+ if value == nil {+ value = []byte{}+ }++ return TXTEntry{Key: key, Value: value}+}++// NewTXTFlag creates a boolean TXT attribute: a key that is present with no+// value, encoded on the wire as just "key" (RFC 6763 §6.4).+func NewTXTFlag(key string) TXTEntry {+ return TXTEntry{Key: key, Value: nil}+}++// validateTXTEntries checks a slice of TXT entries against the DNS-SD rules+// (RFC 6763 §6.4, §6.7):+// - each key must be non-empty, contain no '=', and be printable US-ASCII;+// - each encoded "key=value" (or bare "key") string must not exceed 255 bytes;+// - keys must be unique, compared case-insensitively.+//+// It returns the first violation encountered, or nil if all entries are valid.+func validateTXTEntries(entries []TXTEntry) error {+ seen := make(map[string]struct{}, len(entries))+ for _, entry := range entries {+ if err := validateTXTKey(entry.Key); err != nil {+ return err+ }++ // Encoded length: "key=value" (with '=') or "key" (boolean attribute).+ encodedLen := len(entry.Key)+ if entry.Value != nil {+ encodedLen += 1 + len(entry.Value) // '=' separator + value bytes+ }+ if encodedLen > maxTXTStringLen {+ return errTXTStringTooLong+ }++ lower := strings.ToLower(entry.Key)+ if _, dup := seen[lower]; dup {+ return errTXTDuplicateKey+ }+ seen[lower] = struct{}{}+ }++ return nil+}++// validateTXTKey checks a single TXT key against RFC 6763 §6.4: it must be+// non-empty, must not contain '=' (0x3D), and must consist solely of+// printable US-ASCII characters (0x20-0x7E).+func validateTXTKey(key string) error {+ if key == "" {+ return errTXTKeyEmpty+ }++ for i := 0; i < len(key); i++ {+ c := key[i]+ switch {+ case c == '=':+ return errTXTKeyHasEquals+ case c < 0x20 || c > 0x7E:+ return errTXTKeyNotASCII+ }+ }++ return nil+}++// encodeTXTRecordStrings converts key/value pairs into the wire-format+// strings for a DNS TXT resource record. Each entry becomes "key=value"+// or just "key" (boolean attribute). Returns an error if any single+// encoded string exceeds 255 bytes (RFC 1035 §3.3.14) or a key is empty.+//+// An empty input slice returns a single empty string, which represents+// the minimum valid TXT record (RFC 6763 §6.1).+func encodeTXTRecordStrings(pairs []TXTEntry) ([]string, error) {+ if len(pairs) == 0 {+ return []string{""}, nil+ }++ out := make([]string, 0, len(pairs))+ for _, kv := range pairs {+ if kv.Key == "" {+ return nil, errTXTKeyEmpty+ }++ var s string+ if kv.Value == nil {+ // Boolean attribute: key only, no '='+ s = kv.Key+ } else {+ // key=value (value may be empty)+ s = kv.Key + "=" + string(kv.Value)+ }++ if len(s) > maxTXTStringLen {+ return nil, errTXTStringTooLong+ }+ out = append(out, s)+ }++ return out, nil+}++// decodeTXTRecordStrings parses wire-format TXT record strings back into+// key/value pairs. Duplicate keys are deduplicated: only the first+// occurrence is kept (RFC 6763 §6.4). Strings where the key is empty+// (i.e. starting with '=') are silently ignored (RFC 6763 §6.4).+// Empty strings are skipped.+func decodeTXTRecordStrings(ss []string) []TXTEntry {+ var out []TXTEntry+ seen := make(map[string]struct{})++ for _, s := range ss {+ if s == "" {+ continue+ }++ var kv TXTEntry+ if before, after, ok := strings.Cut(s, "="); ok {+ kv.Key = before+ kv.Value = []byte(after)+ } else {+ // Boolean attribute (no '=')+ kv.Key = s+ kv.Value = nil+ }++ // Empty key → silently ignore (RFC 6763 §6.4)+ if kv.Key == "" {+ continue+ }++ // Deduplicate: case-insensitive, keep first (RFC 6763 §6.4)+ lower := strings.ToLower(kv.Key)+ if _, exists := seen[lower]; exists {+ continue+ }+ seen[lower] = struct{}{}++ out = append(out, kv)+ }++ return out+}++// buildPTRResource creates a PTR resource record.+//+// Name is the query name (e.g. "_http._tcp.local.").+// Target is what the PTR points to (e.g. "My Web._http._tcp.local.").+// TTL is typically browseTTL (4500) for browsing PTRs (RFC 6762 §10).+func buildPTRResource(name, target string, ttl uint32) (dnsmessage.Resource, error) {+ n, err := dnsmessage.NewName(name)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ targetName, err := dnsmessage.NewName(target)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ return dnsmessage.Resource{+ Header: dnsmessage.ResourceHeader{+ Name: n,+ Type: dnsmessage.TypePTR,+ Class: dnsmessage.ClassINET,+ TTL: ttl,+ },+ Body: &dnsmessage.PTRResource{PTR: targetName},+ }, nil+}++// buildSRVResource creates an SRV resource record.+//+// Name is the service instance FQDN (e.g. "My Web._http._tcp.local.").+// Target is the hostname (e.g. "myhost.local.").+// TTL is typically responseTTL (120) for host-scoped records (RFC 6762 §10).+func buildSRVResource(name, target string, port, priority, weight uint16, ttl uint32) (dnsmessage.Resource, error) {+ n, err := dnsmessage.NewName(name)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ targetName, err := dnsmessage.NewName(target)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ return dnsmessage.Resource{+ Header: dnsmessage.ResourceHeader{+ Name: n,+ Type: dnsmessage.TypeSRV,+ Class: dnsmessage.ClassINET,+ TTL: ttl,+ },+ Body: &dnsmessage.SRVResource{+ Priority: priority,+ Weight: weight,+ Port: port,+ Target: targetName,+ },+ }, nil+}++// buildTXTResource creates a TXT resource record.+//+// Name is the service instance FQDN.+// The txts slice contains pre-encoded TXT strings (each ≤ 255 bytes).+// TTL is typically browseTTL (4500) for TXT records (RFC 6762 §10).+func buildTXTResource(name string, txts []string, ttl uint32) (dnsmessage.Resource, error) {+ n, err := dnsmessage.NewName(name)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ return dnsmessage.Resource{+ Header: dnsmessage.ResourceHeader{+ Name: n,+ Type: dnsmessage.TypeTXT,+ Class: dnsmessage.ClassINET,+ TTL: ttl,+ },+ Body: &dnsmessage.TXTResource{TXT: txts},+ }, nil+}++// buildAResource creates an A resource record for an IPv4 address.+//+// TTL is typically responseTTL (120) for host address records (RFC 6762 §10).+func buildAResource(name string, addr netip.Addr, ttl uint32) (dnsmessage.Resource, error) {+ n, err := dnsmessage.NewName(name)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ ipBuf, err := ipv4ToBytes(addr)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ return dnsmessage.Resource{+ Header: dnsmessage.ResourceHeader{+ Name: n,+ Type: dnsmessage.TypeA,+ Class: dnsmessage.ClassINET,+ TTL: ttl,+ },+ Body: &dnsmessage.AResource{A: ipBuf},+ }, nil+}++// buildAAAAResource creates an AAAA resource record for an IPv6 address.+//+// TTL is typically responseTTL (120) for host address records (RFC 6762 §10).+func buildAAAAResource(name string, addr netip.Addr, ttl uint32) (dnsmessage.Resource, error) {+ n, err := dnsmessage.NewName(name)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ ipBuf, err := ipv6ToBytes(addr)+ if err != nil {+ return dnsmessage.Resource{}, err+ }++ return dnsmessage.Resource{+ Header: dnsmessage.ResourceHeader{+ Name: n,+ Type: dnsmessage.TypeAAAA,+ Class: dnsmessage.ClassINET,+ TTL: ttl,+ },+ Body: &dnsmessage.AAAAResource{AAAA: ipBuf},+ }, nil+}++// parsePTRTarget extracts the target name string from a PTR resource body.+func parsePTRTarget(body dnsmessage.ResourceBody) (string, error) {+ ptr, ok := body.(*dnsmessage.PTRResource)+ if !ok {+ return "", errNotPTRResource+ }++ return ptr.PTR.String(), nil+}++// parseSRVData extracts the target hostname, port, priority, and weight+// from an SRV resource body.+func parseSRVData(body dnsmessage.ResourceBody) (target string, port, priority, weight uint16, err error) {+ srv, ok := body.(*dnsmessage.SRVResource)+ if !ok {+ return "", 0, 0, 0, errNotSRVResource+ }++ return srv.Target.String(), srv.Port, srv.Priority, srv.Weight, nil+}++// parseTXTData extracts the string slice from a TXT resource body.+func parseTXTData(body dnsmessage.ResourceBody) ([]string, error) {+ txt, ok := body.(*dnsmessage.TXTResource)+ if !ok {+ return nil, errNotTXTResource+ }++ return txt.TXT, nil+}diff --git a/client-core/third_party/pion-mdns/server.go b/client-core/third_party/pion-mdns/server.gonew file mode 100644index 0000000..54784db--- /dev/null+++ b/client-core/third_party/pion-mdns/server.go@@ -0,0 +1,1280 @@+// SPDX-FileCopyrightText: The Pion community <https://pion.ly>+// SPDX-License-Identifier: MIT++package mdns++import (+ "fmt"+ "github.com/wlynxg/anet"+ "net"+ "net/netip"+ "slices"+ "strings"+ "sync"+ "time"++ "github.com/pion/logging"+ "golang.org/x/net/dns/dnsmessage"+ "golang.org/x/net/ipv4"+ "golang.org/x/net/ipv6"+)++type ipToBytesError struct {+ addr netip.Addr+ expectedType string+}++func (err ipToBytesError) Error() string {+ return fmt.Sprintf("ip (%s) is not %s", err.addr, err.expectedType)+}++// ipv4ToBytes converts an IPv4 address to a 4-byte array.+// Assumes ipv4-to-ipv6 mapping has been checked.+func ipv4ToBytes(ipAddr netip.Addr) ([4]byte, error) {+ if !ipAddr.Is4() {+ return [4]byte{}, ipToBytesError{ipAddr, "IPv4"}+ }++ md, err := ipAddr.MarshalBinary()+ if err != nil {+ return [4]byte{}, err+ }++ // net.IPs are stored in big endian / network byte order+ var out [4]byte+ copy(out[:], md)++ return out, nil+}++// ipv6ToBytes converts an IPv6 address to a 16-byte array.+// Assumes ipv4-to-ipv6 mapping has been checked.+func ipv6ToBytes(ipAddr netip.Addr) ([16]byte, error) {+ if !ipAddr.Is6() {+ return [16]byte{}, ipToBytesError{ipAddr, "IPv6"}+ }+ md, err := ipAddr.MarshalBinary()+ if err != nil {+ return [16]byte{}, err+ }++ // net.IPs are stored in big endian / network byte order+ var out [16]byte+ copy(out[:], md)++ return out, nil+}++// createAnswer creates a DNS answer message for an A or AAAA query.+func (s *server) createAnswer(id uint16, question dnsmessage.Question, addr netip.Addr,+ isUnicast bool,+) (dnsmessage.Message, error) {+ packedName, err := dnsmessage.NewName(question.Name.String())+ if err != nil {+ return dnsmessage.Message{}, err+ }++ msg := dnsmessage.Message{+ Header: dnsmessage.Header{+ ID: id,+ Response: true,+ Authoritative: true,+ },+ Answers: []dnsmessage.Resource{+ {+ Header: dnsmessage.ResourceHeader{+ Class: dnsmessage.ClassINET,+ Name: packedName,+ TTL: s.ttl,+ },+ },+ },+ }++ // include question in answer if specified for this answer (such as unicast: Spec 6.7.)+ if isUnicast {+ msg.Questions = []dnsmessage.Question{question}+ }++ if addr.Is4() {+ ipBuf, err := ipv4ToBytes(addr)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Answers[0].Header.Type = dnsmessage.TypeA+ msg.Answers[0].Body = &dnsmessage.AResource{+ A: ipBuf,+ }+ } else if addr.Is6() {+ // we will lose the zone here, but the receiver can reconstruct it+ ipBuf, err := ipv6ToBytes(addr)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Answers[0].Header.Type = dnsmessage.TypeAAAA+ msg.Answers[0].Body = &dnsmessage.AAAAResource{+ AAAA: ipBuf,+ }+ }++ return msg, nil+}++// answerWriter is the interface for sending DNS answers.+type answerWriter interface {+ writeAnswer(ifIndex int, b []byte, hasLoopbackData, hasIPv6Zone bool, unicastDst *net.UDPAddr)+}++// server handles mDNS server operations (responding to queries).+type server struct {+ log logging.LeveledLogger+ name string+ handler *questionHandler+ writer answerWriter+ ttl uint32++ mu sync.RWMutex+ services []ServiceInstance+ txtAnnouncementGeneration uint64+ txtAnnouncementGenerations map[registeredServiceKey]uint64+}++type registeredServiceKey struct {+ instance string+ service string+}++// newServer creates a new mDNS server.+func newServer(+ log logging.LeveledLogger,+ name string,+ writer answerWriter,+ localNames []string,+ localAddress net.IP,+ ifaces map[int]netInterface,+ hasIPv4 bool,+ dstAddr4, dstAddr6 *net.UDPAddr,+ ttl uint32,+ services []ServiceInstance,+ allowedRecordTypes []dnsmessage.Type,+) *server {+ srv := &server{+ log: log,+ name: name,+ writer: writer,+ ttl: ttl,+ services: services,+ }+ srv.handler = newQuestionHandler(+ localNames,+ localAddress,+ ifaces,+ hasIPv4,+ srv, // server implements answerSender+ writer,+ log,+ name,+ dstAddr4,+ dstAddr6,+ allowedRecordTypes,+ )++ return srv+}++// registerService adds a DNS-SD service to the server.+func (s *server) registerService(svc ServiceInstance) {+ s.mu.Lock()+ defer s.mu.Unlock()++ s.services = append(s.services, svc)+}++// updateTXT replaces a registered service's TXT data and sends the first+// cache-flushed announcement.+// https://www.rfc-editor.org/rfc/rfc6762.html#section-8.3+func (s *server) updateTXT(instance, service string, text []TXTEntry) (uint64, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ for i := range s.services {+ if s.services[i].Instance != instance || s.services[i].Service != service {+ continue+ }+ if txtEntriesEqual(s.services[i].Text, text) {+ return 0, nil+ }++ updated := s.services[i]+ updated.Text = cloneTXTEntries(text)++ txtStrings, err := encodeTXTRecordStrings(updated.Text)+ if err != nil {+ return 0, err+ }+ rawAnnouncement, err := s.packTXTAnnouncement(&updated, txtStrings)+ if err != nil {+ return 0, err+ }++ s.txtAnnouncementGeneration+++ if s.txtAnnouncementGeneration == 0 {+ s.txtAnnouncementGeneration+++ }+ if s.txtAnnouncementGenerations == nil {+ s.txtAnnouncementGenerations = make(map[registeredServiceKey]uint64)+ }+ generation := s.txtAnnouncementGeneration+ s.txtAnnouncementGenerations[registeredServiceKey{instance: instance, service: service}] = generation++ s.services[i] = updated+ s.writer.writeAnswer(-1, rawAnnouncement, false, false, nil)++ return generation, nil+ }++ return 0, errServiceNotFound+}++func (s *server) repeatTXTAnnouncement(instance, service string, generation uint64) error {+ s.mu.Lock()+ defer s.mu.Unlock()++ key := registeredServiceKey{instance: instance, service: service}+ if s.txtAnnouncementGenerations[key] != generation {+ return nil+ }+ for i := range s.services {+ if s.services[i].Instance != instance || s.services[i].Service != service {+ continue+ }++ txtStrings, err := encodeTXTRecordStrings(s.services[i].Text)+ if err != nil {+ return err+ }+ rawAnnouncement, err := s.packTXTAnnouncement(&s.services[i], txtStrings)+ if err != nil {+ return err+ }+ s.writer.writeAnswer(-1, rawAnnouncement, false, false, nil)++ return nil+ }++ return nil+}++func (s *server) packTXTAnnouncement(svc *ServiceInstance, txtStrings []string) ([]byte, error) {+ txtRecord, err := buildTXTResource(svc.serviceInstanceName(), txtStrings, s.ttl)+ if err != nil {+ return nil, err+ }+ txtRecord.Header.Class |= rrClassCacheFlush++ return (&dnsmessage.Message{+ Header: dnsmessage.Header{Response: true, Authoritative: true},+ Answers: []dnsmessage.Resource{txtRecord},+ }).Pack()+}++// unregisterService removes a DNS-SD service from the server by instance+service match.+func (s *server) unregisterService(instance, service string) {+ s.mu.Lock()+ defer s.mu.Unlock()++ for i := len(s.services) - 1; i >= 0; i-- {+ if s.services[i].Instance == instance && s.services[i].Service == service {+ s.services = append(s.services[:i], s.services[i+1:]...)+ delete(s.txtAnnouncementGenerations, registeredServiceKey{instance: instance, service: service})++ return+ }+ }+}++// getServices returns a snapshot of registered services.+func (s *server) getServices() []ServiceInstance {+ s.mu.RLock()+ defer s.mu.RUnlock()++ out := make([]ServiceInstance, len(s.services))+ copy(out, s.services)++ return out+}++// sendAnswer implements answerSender interface.+func (s *server) sendAnswer(+ queryID uint16, question dnsmessage.Question, ifIndex int,+ addr netip.Addr, dst *net.UDPAddr, isUnicast bool,+) {+ answer, err := s.createAnswer(queryID, question, addr, isUnicast)+ if err != nil {+ s.log.Warnf("[%s] failed to create mDNS answer %v", s.name, err)++ return+ }++ rawAnswer, err := answer.Pack()+ if err != nil {+ s.log.Warnf("[%s] failed to construct mDNS packet %v", s.name, err)++ return+ }++ s.writer.writeAnswer(+ ifIndex,+ rawAnswer,+ addr.IsLoopback(),+ addr.Is6() && addr.Zone() != "",+ dst,+ )+}++// serverConfig holds the configuration for a Server.+// This is populated by applying ServerOption functions.+type serverConfig struct {+ // name is the name of the server used for logging purposes.+ name string++ // localNames are the names that we will generate answers for+ // when we get questions.+ localNames []string++ // localAddress will override the published address with the given IP+ // when set. Otherwise, the automatically determined address will be used.+ localAddress net.IP++ // loggerFactory is used to create a logger for the server.+ loggerFactory logging.LoggerFactory++ // includeLoopback will include loopback interfaces to be eligible for answers.+ includeLoopback bool++ // interfaces will override the interfaces used for answers.+ interfaces []net.Interface++ // allowedRecordTypes limits which DNS record types the server will process.+ // If empty (default), all record types are allowed - no filtering is applied.+ // For WebRTC/ICE legacy behavior, set to {dnsmessage.TypeA, dnsmessage.TypeAAAA}.+ allowedRecordTypes []dnsmessage.Type++ // responseTTL is the TTL (in seconds) for DNS response records.+ // Defaults to 120 seconds per RFC 6762 recommendation.+ responseTTL uint32++ // services are the DNS-SD services to advertise (RFC 6763).+ services []ServiceInstance++ // cacheRefresh enables proactive cache refresh per RFC 6762 §5.2.+ // When true, actively-monitored records are re-queried at 80/85/90/95%+ // of their TTL. Defaults to true for NewServer, false for legacy Server.+ cacheRefresh bool++ // refreshCheckInterval is how often the refresh loop checks for+ // records due for refresh. Zero means use defaultRefreshCheckInterval.+ refreshCheckInterval time.Duration++ // queryInterval is how ofen the client check records due for query.+ // Zero means use defaultQueryInterval.+ queryInterval time.Duration+}++// NewServer creates a new mDNS server with the given options.+//+// At least one of the multicast packet connections must be non-nil.+// The presence of each IP type of PacketConn will dictate what kinds+// of questions are sent for queries. That is, if an ipv6.PacketConn is+// provided, then AAAA questions will be sent. A questions will only be+// sent if an ipv4.PacketConn is also provided.+//+// Example:+//+// // Create multicast listeners+// addr4, _ := net.ResolveUDPAddr("udp4", mdns.DefaultAddressIPv4)+// l4, _ := net.ListenUDP("udp4", addr4)+//+// addr6, _ := net.ResolveUDPAddr("udp6", mdns.DefaultAddressIPv6)+// l6, _ := net.ListenUDP("udp6", addr6)+//+// // Create server with options+// server, err := mdns.NewServer(+// ipv4.NewPacketConn(l4),+// ipv6.NewPacketConn(l6),+// mdns.WithLocalNames("myservice.local"),+// )+//+//nolint:gocognit,gocyclo,cyclop,maintidx+func NewServer(+ multicastPktConnV4 *ipv4.PacketConn,+ multicastPktConnV6 *ipv6.PacketConn,+ opts ...ServerOption,+) (*Conn, error) {+ // Apply options to config+ cfg := &serverConfig{cacheRefresh: true}+ for _, opt := range opts {+ if err := opt.applyServer(cfg); err != nil {+ return nil, err+ }+ }++ loggerFactory := cfg.loggerFactory+ if loggerFactory == nil {+ loggerFactory = logging.NewDefaultLoggerFactory()+ }+ log := loggerFactory.NewLogger("mdns")++ // Default TTL per RFC 6762 recommendation+ if cfg.responseTTL == 0 {+ cfg.responseTTL = responseTTL+ }++ conn := &Conn{+ queryInterval: cfg.queryInterval,+ log: log,+ cache: newCache(time.Now),+ stopBackground: make(chan struct{}),+ cacheRefresh: cfg.cacheRefresh,+ refreshCheckInterval: cfg.refreshCheckInterval,+ closed: make(chan any),+ }+ conn.name = cfg.name+ if conn.name == "" {+ conn.name = fmt.Sprintf("%p", &conn)+ }++ if multicastPktConnV4 == nil && multicastPktConnV6 == nil {+ return nil, errNoPacketConn+ }++ ifaces := cfg.interfaces+ if ifaces == nil {+ var err error+ ifaces, err = anet.Interfaces() // PasteFerry:Android 11 起 net.Interfaces() 被拦+ if err != nil {+ return nil, err+ }+ }++ var unicastPktConnV4 *ipv4.PacketConn+ {+ addr4, err := net.ResolveUDPAddr("udp4", "0.0.0.0:0")+ if err != nil {+ return nil, err+ }++ unicastConnV4, err := net.ListenUDP("udp4", addr4)+ if err != nil {+ log.Warnf(+ "[%s] failed to listen on unicast IPv4 %s: %s; will not be able to receive unicast responses on IPv4",+ conn.name, addr4, err,+ )+ } else {+ unicastPktConnV4 = ipv4.NewPacketConn(unicastConnV4)+ }+ }++ var unicastPktConnV6 *ipv6.PacketConn+ {+ addr6, err := net.ResolveUDPAddr("udp6", "[::]:")+ if err != nil {+ return nil, err+ }++ unicastConnV6, err := net.ListenUDP("udp6", addr6)+ if err != nil {+ log.Warnf(+ "[%s] failed to listen on unicast IPv6 %s: %s; will not be able to receive unicast responses on IPv6",+ conn.name, addr6, err,+ )+ } else {+ unicastPktConnV6 = ipv6.NewPacketConn(unicastConnV6)+ }+ }++ multicastGroup4 := net.IPv4(224, 0, 0, 251)+ multicastGroupAddr4 := &net.UDPAddr{IP: multicastGroup4}++ // FF02::FB+ multicastGroup6 := net.IP{0xff, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xfb}+ multicastGroupAddr6 := &net.UDPAddr{IP: multicastGroup6}++ inboundBufferSize := 0+ joinErrCount := 0+ ifacesToUse := make(map[int]netInterface, len(ifaces))+ for i := range ifaces {+ ifc := ifaces[i]+ if !cfg.includeLoopback && ifc.Flags&net.FlagLoopback == net.FlagLoopback {+ continue+ }+ if ifc.Flags&net.FlagUp == 0 {+ continue+ }++ addrs, err := anet.InterfaceAddrsByInterface(&ifc) // PasteFerry:同上,ifc.Addrs() 也会被拦+ if err != nil {+ continue+ }+ var supportsV4, supportsV6 bool+ ifcIPAddrs := make([]netip.Addr, 0, len(addrs))+ for _, addr := range addrs {+ var ipToConv net.IP+ switch addr := addr.(type) {+ case *net.IPNet:+ ipToConv = addr.IP+ case *net.IPAddr:+ ipToConv = addr.IP+ default:+ continue+ }++ ipAddr, ok := netip.AddrFromSlice(ipToConv)+ if !ok {+ continue+ }+ if multicastPktConnV4 != nil {+ // don't want mapping since we also support IPv4/A+ ipAddr = ipAddr.Unmap()+ }+ ipAddr = addrWithOptionalZone(ipAddr, ifc.Name)++ if ipAddr.Is6() && !ipAddr.Is4In6() {+ supportsV6 = true+ } else {+ // we'll claim we support v4 but defer if we send it or not+ // based on IPv4-to-IPv6 mapping rules later (search for Is4In6 below)+ supportsV4 = true+ }+ ifcIPAddrs = append(ifcIPAddrs, ipAddr)+ }+ if !supportsV4 && !supportsV6 {+ continue+ }++ var atLeastOneJoin bool+ if supportsV4 && multicastPktConnV4 != nil {+ if err := multicastPktConnV4.JoinGroup(&ifc, multicastGroupAddr4); err == nil {+ atLeastOneJoin = true+ }+ }+ if supportsV6 && multicastPktConnV6 != nil {+ if err := multicastPktConnV6.JoinGroup(&ifc, multicastGroupAddr6); err == nil {+ atLeastOneJoin = true+ }+ }+ if !atLeastOneJoin {+ joinErrCount++++ continue+ }++ ifacesToUse[ifc.Index] = netInterface{+ Interface: ifc,+ ipAddrs: ifcIPAddrs,+ supportsV4: supportsV4,+ supportsV6: supportsV6,+ }+ if ifc.MTU > inboundBufferSize {+ inboundBufferSize = ifc.MTU+ }+ }++ if len(ifacesToUse) == 0 {+ return nil, errNoUsableInterfaces+ }+ if inboundBufferSize == 0 {+ return nil, errNoPositiveMTUFound+ }+ if inboundBufferSize > maxPacketSize {+ inboundBufferSize = maxPacketSize+ }+ if joinErrCount >= len(ifaces) {+ return nil, errJoiningMulticastGroup+ }++ dstAddr4, err := net.ResolveUDPAddr("udp4", destinationAddress4)+ if err != nil {+ return nil, err+ }++ dstAddr6, err := net.ResolveUDPAddr("udp6", destinationAddress6)+ if err != nil {+ return nil, err+ }++ var localNames []string+ for _, l := range cfg.localNames {+ localNames = append(localNames, l+".")+ }++ conn.dstAddr4 = dstAddr4+ conn.dstAddr6 = dstAddr6+ conn.localNames = localNames+ conn.ifaces = ifacesToUse++ conn.multicastPktConnV4 = configurePacketConn4(multicastPktConnV4, conn.name, "multicast", log)+ conn.multicastPktConnV6 = configurePacketConn6(multicastPktConnV6, conn.name, "multicast", log)+ conn.unicastPktConnV4 = configurePacketConn4(unicastPktConnV4, conn.name, "unicast", log)+ conn.unicastPktConnV6 = configurePacketConn6(unicastPktConnV6, conn.name, "unicast", log)++ // Create client and server for processing messages+ conn.client = newClient(+ log,+ conn.name,+ conn, // Conn implements questionWriter+ multicastPktConnV4 != nil,+ multicastPktConnV6 != nil,+ conn.cache,+ )+ // Ensure each service has the host set to the server's hostname.+ for i := range cfg.services {+ if cfg.services[i].Host == "" && len(localNames) > 0 {+ cfg.services[i].Host = localNames[0]+ }+ }++ conn.server = newServer(+ log,+ conn.name,+ conn, // Conn implements answerWriter+ localNames,+ cfg.localAddress,+ ifacesToUse,+ multicastPktConnV4 != nil,+ dstAddr4,+ dstAddr6,+ cfg.responseTTL,+ cfg.services,+ cfg.allowedRecordTypes,+ )++ if cfg.includeLoopback {+ // Enable loopback for efficient self-messaging without going through the network stack.+ enableLoopback4(multicastPktConnV4, conn.name, "multicast", log)+ enableLoopback6(multicastPktConnV6, conn.name, "multicast", log)+ enableLoopback4(unicastPktConnV4, conn.name, "unicast", log)+ enableLoopback6(unicastPktConnV6, conn.name, "unicast", log)+ }++ // https://www.rfc-editor.org/rfc/rfc6762.html#section-17+ // Multicast DNS messages carried by UDP may be up to the IP MTU of the+ // physical interface, less the space required for the IP header (20+ // bytes for IPv4; 40 bytes for IPv6) and the UDP header (8 bytes).+ started := make(chan struct{})+ go conn.start(started, inboundBufferSize-20-8, cfg)+ <-started++ return conn, nil+}++// Server establishes a mDNS connection over an existing conn.+//+// Deprecated: Use NewServer with functional options instead.+// This function is retained for backward compatibility with existing code.+//+// This function applies WebRTC/ICE legacy behavior by default, only processing+// A and AAAA record types. The equivalent NewServer call is:+//+// conn, err := mdns.NewServer(+// ipv4.NewPacketConn(l4),+// ipv6.NewPacketConn(l6),+// mdns.WithLocalNames("example.local"),+// mdns.WithRecordTypes(dnsmessage.TypeA, dnsmessage.TypeAAAA),+// )+//+// For full mDNS/DNS-SD support (all record types), omit WithRecordTypes.+func Server(+ multicastPktConnV4 *ipv4.PacketConn,+ multicastPktConnV6 *ipv6.PacketConn,+ config *Config,+) (*Conn, error) {+ if config == nil {+ return nil, errNilConfig+ }++ // Convert legacy Config to ServerOptions+ opts := []ServerOption{+ // Legacy behavior: only handle A/AAAA records (WebRTC/ICE compatibility)+ WithRecordTypes(dnsmessage.TypeA, dnsmessage.TypeAAAA),+ // Legacy behavior: no proactive cache refresh.+ WithCacheRefresh(false),+ }+ if config.Name != "" {+ opts = append(opts, WithName(config.Name))+ }+ if len(config.LocalNames) > 0 {+ opts = append(opts, WithLocalNames(config.LocalNames...))+ }+ if config.LocalAddress != nil {+ opts = append(opts, WithLocalAddress(config.LocalAddress))+ }+ if config.LoggerFactory != nil {+ opts = append(opts, WithLoggerFactory(config.LoggerFactory))+ }+ if config.IncludeLoopback {+ opts = append(opts, WithIncludeLoopback(true))+ }+ if len(config.Interfaces) > 0 {+ opts = append(opts, WithInterfaces(config.Interfaces...))+ }+ if config.QueryInterval != 0 {+ opts = append(opts, WithQueryInterval(config.QueryInterval))+ }++ conn, err := NewServer(multicastPktConnV4, multicastPktConnV6, opts...)+ if err != nil {+ return nil, err+ }++ return conn, nil+}++// sendServiceAnswer builds and sends a DNS-SD response for a service instance.+// Per RFC 6763 §12, additional records are included:+// - PTR answer → SRV + TXT additional, plus A/AAAA for the host+// - SRV answer → A/AAAA additional for the host+func (s *server) sendServiceAnswer(+ queryID uint16, question dnsmessage.Question, ifIndex int,+ svc *ServiceInstance, addr netip.Addr, dst *net.UDPAddr, isUnicast bool,+) {+ msg, err := s.createServiceAnswer(queryID, question, svc, addr, isUnicast)+ if err != nil {+ s.log.Warnf("[%s] failed to create DNS-SD answer %v", s.name, err)++ return+ }++ rawAnswer, err := msg.Pack()+ if err != nil {+ s.log.Warnf("[%s] failed to pack DNS-SD answer %v", s.name, err)++ return+ }++ s.writer.writeAnswer(+ ifIndex,+ rawAnswer,+ addr.IsLoopback(),+ addr.Is6() && addr.Zone() != "",+ dst,+ )+}++// createServiceAnswer builds a DNS message for a DNS-SD service query.+//+//nolint:cyclop+func (s *server) createServiceAnswer(+ queryID uint16, question dnsmessage.Question,+ svc *ServiceInstance, addr netip.Addr, isUnicast bool,+) (dnsmessage.Message, error) {+ msg := dnsmessage.Message{+ Header: dnsmessage.Header{+ ID: queryID,+ Response: true,+ Authoritative: true,+ },+ }++ if isUnicast {+ msg.Questions = []dnsmessage.Question{question}+ }++ instanceName := svc.serviceInstanceName()+ svcName := svc.serviceName()++ switch question.Type {+ case dnsmessage.TypePTR:+ // PTR answer: service name → instance name+ ptrRec, err := buildPTRResource(svcName, instanceName, browseTTL)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Answers = []dnsmessage.Resource{ptrRec}++ // Additional: SRV + TXT + address records (RFC 6763 §12.1)+ additional, err := s.buildServiceAdditional(svc, instanceName, addr)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Additionals = additional++ case dnsmessage.TypeSRV:+ // SRV answer+ srvRec, err := buildSRVResource(instanceName, svc.Host, svc.Port, svc.Priority, svc.Weight, s.ttl)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Answers = []dnsmessage.Resource{srvRec}++ // Additional: address records (RFC 6763 §12.2)+ addrRec, err := s.buildAddressResource(svc.Host, addr)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Additionals = []dnsmessage.Resource{addrRec}++ case dnsmessage.TypeTXT:+ // TXT answer+ txtStrings, err := encodeTXTRecordStrings(svc.Text)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ txtRec, err := buildTXTResource(instanceName, txtStrings, s.ttl)+ if err != nil {+ return dnsmessage.Message{}, err+ }+ msg.Answers = []dnsmessage.Resource{txtRec}++ default:+ return dnsmessage.Message{}, errUnhandledServiceQuestionType+ }++ return msg, nil+}++// buildServiceAdditional creates the additional records for a PTR response.+func (s *server) buildServiceAdditional(+ svc *ServiceInstance, instanceName string, addr netip.Addr,+) ([]dnsmessage.Resource, error) {+ var additional []dnsmessage.Resource++ srvRec, err := buildSRVResource(instanceName, svc.Host, svc.Port, svc.Priority, svc.Weight, s.ttl)+ if err != nil {+ return nil, err+ }+ additional = append(additional, srvRec)++ txtStrings, err := encodeTXTRecordStrings(svc.Text)+ if err != nil {+ return nil, err+ }+ txtRec, err := buildTXTResource(instanceName, txtStrings, s.ttl)+ if err != nil {+ return nil, err+ }+ additional = append(additional, txtRec)++ addrRec, err := s.buildAddressResource(svc.Host, addr)+ if err != nil {+ return nil, err+ }+ additional = append(additional, addrRec)++ return additional, nil+}++// buildAddressResource creates an A or AAAA resource for the given host and address.+func (s *server) buildAddressResource(host string, addr netip.Addr) (dnsmessage.Resource, error) {+ if addr.Is4() {+ return buildAResource(host, addr, s.ttl)+ }++ return buildAAAAResource(host, addr, s.ttl)+}++// answerSender is the callback interface for sending DNS answers.+type answerSender interface {+ sendAnswer(+ queryID uint16, question dnsmessage.Question, ifIndex int,+ addr netip.Addr, dst *net.UDPAddr, isUnicast bool,+ )+ sendServiceAnswer(+ queryID uint16, question dnsmessage.Question, ifIndex int,+ svc *ServiceInstance, addr netip.Addr, dst *net.UDPAddr, isUnicast bool,+ )+ getServices() []ServiceInstance+}++// questionHandler processes incoming mDNS questions (server role).+// It matches questions against configured local names and sends answers.+type questionHandler struct {+ localNames []string+ localAddress net.IP+ ifaces map[int]netInterface+ hasIPv4 bool+ sender answerSender+ writer answerWriter+ log logging.LeveledLogger+ name string+ dstAddr4 *net.UDPAddr+ dstAddr6 *net.UDPAddr+ allowedRecordTypes []dnsmessage.Type+}++// newQuestionHandler creates a new questionHandler.+func newQuestionHandler(+ localNames []string,+ localAddress net.IP,+ ifaces map[int]netInterface,+ hasIPv4 bool,+ sender answerSender,+ writer answerWriter,+ log logging.LeveledLogger,+ name string,+ dstAddr4, dstAddr6 *net.UDPAddr,+ allowedRecordTypes []dnsmessage.Type,+) *questionHandler {+ return &questionHandler{+ localNames: localNames,+ localAddress: localAddress,+ ifaces: ifaces,+ hasIPv4: hasIPv4,+ sender: sender,+ writer: writer,+ log: log,+ name: name,+ dstAddr4: dstAddr4,+ dstAddr6: dstAddr6,+ allowedRecordTypes: allowedRecordTypes,+ }+}++// isRecordTypeAllowed checks if the given record type is allowed by the filter.+// If no filter is configured (empty slice), all types are allowed.+func (h *questionHandler) isRecordTypeAllowed(qtype dnsmessage.Type) bool {+ if len(h.allowedRecordTypes) == 0 {+ return true+ }++ return slices.Contains(h.allowedRecordTypes, qtype)+}++// handle processes a DNS message containing questions.+// It iterates through questions and sends answers for matching local names+// and registered DNS-SD services.+//+//nolint:gocognit,gocyclo,cyclop+func (h *questionHandler) handle(ctx *messageContext, msg *dnsmessage.Message) {+ for _, question := range msg.Questions {+ if !h.isRecordTypeAllowed(question.Type) {+ continue+ }++ // Determine if we should reply via unicast+ // https://datatracker.ietf.org/doc/html/rfc6762#section-6+ isQU := (question.Class & qClassUnicastResponse) != 0+ isLegacy := ctx.source.Port != 5353 // legacy query (Section 6.7)+ isDirect := len(ctx.pktDst) != 0 && // direct unicast query+ !ctx.pktDst.Equal(h.dstAddr4.IP) &&+ !ctx.pktDst.Equal(h.dstAddr6.IP)+ shouldReplyUnicast := isQU || isLegacy || isDirect++ var dst *net.UDPAddr+ if shouldReplyUnicast {+ dst = ctx.source+ }++ switch question.Type {+ case dnsmessage.TypeA, dnsmessage.TypeAAAA:+ h.handleAddressQuestion(ctx, msg.Header.ID, question, dst, shouldReplyUnicast)+ case dnsmessage.TypePTR:+ h.handlePTRQuestion(ctx, msg.Header.ID, question, dst, shouldReplyUnicast)+ case dnsmessage.TypeSRV, dnsmessage.TypeTXT:+ h.handleServiceRecordQuestion(ctx, msg.Header.ID, question, dst, shouldReplyUnicast)+ default:+ continue+ }+ }+}++// handleAddressQuestion processes A/AAAA questions against local names.+func (h *questionHandler) handleAddressQuestion(+ ctx *messageContext, queryID uint16, question dnsmessage.Question,+ dst *net.UDPAddr, isUnicast bool,+) {+ queryWantsV4 := question.Type == dnsmessage.TypeA++ for _, localName := range h.localNames {+ if !strings.EqualFold(localName, question.Name.String()) {+ continue+ }++ localAddress := h.resolveLocalAddress(ctx, queryWantsV4, dst)+ if localAddress == nil {+ continue+ }++ h.log.Debugf(+ "[%s] sending response for %s on ifc %d of %s to %s",+ h.name, question.Name, ctx.ifIndex, *localAddress, dst,+ )+ h.sender.sendAnswer(queryID, question, ctx.ifIndex, *localAddress, dst, isUnicast)+ }+}++// handlePTRQuestion processes PTR questions for DNS-SD service browsing and+// service type enumeration.+func (h *questionHandler) handlePTRQuestion(+ ctx *messageContext, queryID uint16, question dnsmessage.Question,+ dst *net.UDPAddr, isUnicast bool,+) {+ services := h.sender.getServices()+ qname := question.Name.String()++ // Check if this is a service type enumeration meta-query (RFC 6763 §9).+ enumName := serviceTypeEnumerationName + ".local."+ if strings.EqualFold(enumName, qname) {+ h.handleServiceTypeEnumeration(ctx, queryID, question, services, dst, isUnicast)++ return+ }++ for i := range services {+ svc := &services[i]+ svcName := svc.serviceName()++ if !strings.EqualFold(svcName, qname) {+ continue+ }++ // Resolve an address for the additional records.+ localAddress := h.resolveLocalAddress(ctx, true, dst)+ if localAddress == nil {+ localAddress = h.resolveLocalAddress(ctx, false, dst)+ }+ if localAddress == nil {+ continue+ }++ h.log.Debugf("[%s] sending PTR response for %s on ifc %d to %s", h.name, qname, ctx.ifIndex, dst)+ h.sender.sendServiceAnswer(queryID, question, ctx.ifIndex, svc, *localAddress, dst, isUnicast)+ }+}++// handleServiceTypeEnumeration responds to the service type enumeration+// meta-query (RFC 6763 §9) by sending a PTR record for each unique+// service type registered.+func (h *questionHandler) handleServiceTypeEnumeration(+ ctx *messageContext, queryID uint16, question dnsmessage.Question,+ services []ServiceInstance, dst *net.UDPAddr, isUnicast bool,+) {+ // Collect unique service types.+ seen := make(map[string]bool)+ var answers []dnsmessage.Resource++ for i := range services {+ svc := &services[i]+ svcName := svc.serviceName()++ if seen[strings.ToLower(svcName)] {+ continue+ }+ seen[strings.ToLower(svcName)] = true++ ptrRec, err := buildPTRResource(+ serviceTypeEnumerationName+".local.",+ svcName,+ browseTTL,+ )+ if err != nil {+ h.log.Warnf("[%s] failed to build service type PTR: %v", h.name, err)++ continue+ }+ answers = append(answers, ptrRec)+ }++ if len(answers) == 0 {+ return+ }++ msg := dnsmessage.Message{+ Header: dnsmessage.Header{+ ID: queryID,+ Response: true,+ Authoritative: true,+ },+ Answers: answers,+ }++ if isUnicast {+ msg.Questions = []dnsmessage.Question{question}+ }++ rawAnswer, err := msg.Pack()+ if err != nil {+ h.log.Warnf("[%s] failed to pack service type enumeration response: %v", h.name, err)++ return+ }++ h.log.Debugf("[%s] sending service type enumeration response on ifc %d to %s", h.name, ctx.ifIndex, dst)+ h.writer.writeAnswer(ctx.ifIndex, rawAnswer, false, false, dst)+}++// handleServiceRecordQuestion processes SRV/TXT questions against registered services.+func (h *questionHandler) handleServiceRecordQuestion(+ ctx *messageContext, queryID uint16, question dnsmessage.Question,+ dst *net.UDPAddr, isUnicast bool,+) {+ services := h.sender.getServices()+ qname := question.Name.String()++ for i := range services {+ svc := &services[i]+ instanceName := svc.serviceInstanceName()++ if !strings.EqualFold(instanceName, qname) {+ continue+ }++ localAddress := h.resolveLocalAddress(ctx, true, dst)+ if localAddress == nil {+ localAddress = h.resolveLocalAddress(ctx, false, dst)+ }+ if localAddress == nil {+ continue+ }++ h.log.Debugf("[%s] sending %v response for %s on ifc %d to %s",+ h.name, question.Type, qname, ctx.ifIndex, dst)+ h.sender.sendServiceAnswer(queryID, question, ctx.ifIndex, svc, *localAddress, dst, isUnicast)+ }+}++// resolveLocalAddress determines the appropriate local address to respond with.+//+//nolint:gocognit,gocyclo,cyclop,nestif+func (h *questionHandler) resolveLocalAddress(ctx *messageContext, queryWantsV4 bool, dst *net.UDPAddr) *netip.Addr {+ var localAddress *netip.Addr+ var err error++ if h.localAddress != nil {+ // Use configured local address+ ipAddr, ok := netip.AddrFromSlice(h.localAddress)+ if !ok {+ h.log.Warnf("[%s] failed to convert config.localAddress '%s' to netip.Addr", h.name, h.localAddress)++ return nil+ }+ if h.hasIPv4 {+ ipAddr = ipAddr.Unmap()+ }+ localAddress = &ipAddr+ } else {+ // Derive address from interface or source+ if ctx.ifIndex != -1 {+ localAddress = h.selectAddressFromInterface(ctx.ifIndex, queryWantsV4)+ }++ if ctx.ifIndex == -1 || localAddress == nil {+ localAddress, err = interfaceForRemote(ctx.source.String())+ if err != nil {+ h.log.Warnf("[%s] failed to get local interface to communicate with %s: %v", h.name, ctx.source.String(), err)++ return nil+ }+ }+ }++ // Validate address matches query type+ if queryWantsV4 {+ if !localAddress.Is4() {+ h.log.Debugf("[%s] have IPv6 address %s to respond with but question is for A not AAAA", h.name, localAddress)++ return nil+ }+ } else {+ if !localAddress.Is6() {+ h.log.Debugf("[%s] have IPv4 address %s to respond with but question is for AAAA not A", h.name, localAddress)++ return nil+ }+ if !isSupportedIPv6(*localAddress, !h.hasIPv4) {+ h.log.Debugf("[%s] got local interface address but not a supported IPv6 address %v", h.name, localAddress)++ return nil+ }+ }++ // Check for link-local address being sent to IPv4 destination+ if dst != nil && len(dst.IP) == net.IPv4len &&+ localAddress.Is6() &&+ localAddress.Zone() != "" &&+ (localAddress.IsLinkLocalUnicast() || localAddress.IsLinkLocalMulticast()) {+ h.log.Debugf("[%s] refusing to send link-local address %s to an IPv4 destination %s", h.name, localAddress, dst)++ return nil+ }++ return localAddress+}++// selectAddressFromInterface selects an appropriate address from the interface.+//+//nolint:gocognit,cyclop,nestif+func (h *questionHandler) selectAddressFromInterface(ifIndex int, queryWantsV4 bool) *netip.Addr {+ ifc, ok := h.ifaces[ifIndex]+ if !ok {+ h.log.Warnf("[%s] no interface for %d", h.name, ifIndex)++ return nil+ }++ var selectedAddrs []netip.Addr+ for _, addr := range ifc.ipAddrs {+ addrCopy := addr++ if queryWantsV4 {+ if addrCopy.Is4In6() {+ addrCopy = addrCopy.Unmap()+ }+ if !addrCopy.Is4() {+ continue+ }+ } else {+ if !addrCopy.Is6() {+ continue+ }+ if !isSupportedIPv6(addrCopy, !h.hasIPv4) {+ h.log.Debugf("[%s] interface %d address not a supported IPv6 address %s", h.name, ifIndex, &addrCopy)++ continue+ }+ }++ selectedAddrs = append(selectedAddrs, addrCopy)+ }++ if len(selectedAddrs) == 0 {+ h.log.Debugf(+ "[%s] failed to find suitable IP for interface %d; deriving address from source instead",+ h.name, ifIndex,+ )++ return nil+ }++ // Choose the best match+ var choice *netip.Addr+ for _, option := range selectedAddrs {+ optCopy := option+ if option.Is4() {+ choice = &optCopy++ break+ }+ if choice == nil || !optCopy.Is4In6() {+ choice = &optCopy+ }+ if !optCopy.Is4In6() {+ break+ }+ }++ return choice+}++func isSupportedIPv6(addr netip.Addr, ipv6Only bool) bool {+ if !addr.Is6() {+ return false+ }+ // IPv4-mapped-IPv6 addresses cannot be connected to unless+ // unmapped.+ if !ipv6Only && addr.Is4In6() {+ return false+ }++ return true+}diff --git a/scripts/build-android.sh b/scripts/build-android.shnew file mode 100755index 0000000..4745032--- /dev/null+++ b/scripts/build-android.sh@@ -0,0 +1,89 @@+#!/usr/bin/env bash+# 构建 Android App(design/phone-sync.md 3.3.7 节):先用 gomobile 把 Go 核心打成 AAR,再由 Flutter 打 APK。+#+# ./scripts/build-android.sh # arm64 的 APK,在 ui/build/app/outputs/flutter-apk/app-release.apk+# # (不放进 release/:那里只放 Release 的 14 个附件)+# ./scripts/build-android.sh --aar # 只打 AAR,之后可以 flutter run --target-platform android-arm64 调试+# ./scripts/build-android.sh --aar --emulator # 给 x86_64 模拟器调试用的 AAR,见下面 --emulator 的说明+#+# 只出 arm64:x86_64 的 Go 核心在 Android 上一启动就被系统杀掉。SQLite 用的 modernc.org/libc+# 在 linux/amd64 上直接调 lstat、open 这类老系统调用,Android 给 x86_64 App 的 seccomp 规则不允许+# (arm64 上本来就没有这些调用,用的是 newfstatat、openat)。x86_64 的模拟器(API 30 起)+# 自带 ARM 转译(ro.dalvik.vm.native.bridge=libndk_translation.so),照样能跑 arm64 的 APK。+#+# 需要 Android SDK 与 NDK(ANDROID_HOME,默认 /usr/local/share/android-commandlinetools)和 JDK 17 以上。+# gomobile、gobind 的版本由 client-core/go.mod 的 tool 一节固定。+#+# 还没有发版签名密钥(phone-task.md C6),APK 用调试密钥签名,只能给内测用。++set -euo pipefail+cd "$(dirname "$0")/.."++export ANDROID_HOME="${ANDROID_HOME:-/usr/local/share/android-commandlinetools}"+if [[ -z "${ANDROID_NDK_HOME:-}" ]]; then+ ANDROID_NDK_HOME="$(ls -d "$ANDROID_HOME"/ndk/* 2>/dev/null | sort -V | tail -1)"+ export ANDROID_NDK_HOME+fi+[[ -d "$ANDROID_NDK_HOME" ]] || {+ echo "找不到 Android NDK:装上 ndk 或设置 ANDROID_NDK_HOME" >&2+ exit 1+}++aar_only=false+emulator=false+for arg in "$@"; do+ case "$arg" in+ --aar) aar_only=true ;;+ --emulator) emulator=true ;;+ *) echo "不认识的参数 $arg" >&2; exit 1 ;;+ esac+done++echo "▶ gomobile、gobind"+tools="$(mktemp -d)"+trap 'chmod -R u+w "$tools" 2>/dev/null; rm -rf "$tools"' EXIT+(cd client-core && GOBIN="$tools" go install golang.org/x/mobile/cmd/gomobile golang.org/x/mobile/cmd/gobind)+export PATH="$tools:$PATH"++# --emulator:x86_64 模拟器的 ARM 转译(ndk_translation)有几条指令执行不了,Go 运行时一跑就 SIGILL:+# - 它给的 AT_HWCAP 报了 CPUID、DIT,却执行不了 MRS MIDR_EL1、MRS DIT;+# - 读不了通用计时器(MRS CNTFRQ_EL0、CNTVCT_EL0),Go 1.26 的 procyield 要用。+# 真机没有这些问题。这里复制一份 Go 工具链改两处再编译:运行时把辅助向量里的 AT_HWCAP、AT_HWCAP2+# 清零(internal/cpu 和 golang.org/x/sys/cpu 都读它们,清零后不用任何可选指令),procyield 不再等待。+# 只给模拟器调试用,不能拿去发布。+# (go build -overlay 不行:工具链在模块缓存里时不许替换其中的文件)+if $emulator; then+ $aar_only || { echo "--emulator 只能和 --aar 一起用" >&2; exit 1; }+ goroot="$tools/goroot"+ cp -Rc "$(cd client-core && go env GOROOT)" "$goroot" 2>/dev/null || cp -R "$(cd client-core && go env GOROOT)" "$goroot"+ chmod -R u+w "$goroot/src/runtime"+ auxv="$goroot/src/runtime/os_linux.go"+ perl -0pi -e 's/(\t\ttag, val := auxv\[i\], auxv\[i\+1\]\n)/$1\t\tif tag == 16 || tag == 26 { \/\/ AT_HWCAP、AT_HWCAP2\n\t\t\tauxv[i+1], val = 0, 0\n\t\t}\n/' "$auxv"+ grep -q 'AT_HWCAP、AT_HWCAP2' "$auxv" || { echo "标准库变了,改不了 $auxv" >&2; exit 1; }+ asm="$goroot/src/runtime/asm_arm64.s"+ perl -pi -e 's/^\tMRS CNTFRQ_EL0, R1$/\tB done \/\/ 模拟器读不了计时器/' "$asm"+ grep -q '模拟器读不了计时器' "$asm" || { echo "标准库变了,改不了 $asm" >&2; exit 1; }+ cat > "$tools/go" <<EOF2+#!/bin/sh+GOROOT="$goroot" GOTOOLCHAIN=local exec "$goroot/bin/go" "\$@"+EOF2+ chmod +x "$tools/go"+fi++echo "▶ Go 核心 AAR"+mkdir -p ui/android/app/libs+# -checklinkname=0:pion 的间接依赖 wlynxg/anet 用了 go:linkname(3.3.2 节第 2 条)+(cd client-core && gomobile bind \+ -target=android/arm64 \+ -androidapi 29 \+ -javapkg=com.pasteferry.core \+ -ldflags="-checklinkname=0 -s -w" \+ -o ../ui/android/app/libs/pasteferry-core.aar \+ ./mobile)+rm -f ui/android/app/libs/pasteferry-core-sources.jar++$aar_only && exit 0++echo "▶ APK"+(cd ui && flutter build apk --release --target-platform android-arm64)+ls -lh ui/build/app/outputs/flutter-apk/app-release.apkdiff --git a/ui/.metadata b/ui/.metadataindex cc64528..5ddf8ec 100644--- a/ui/.metadata+++ b/ui/.metadata@@ -15,6 +15,9 @@ migration:- platform: rootcreate_revision: 6b182d2c7585eba26d4edce0f97630effd256c33base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ - platform: android+ create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33+ base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33- platform: macoscreate_revision: 6b182d2c7585eba26d4edce0f97630effd256c33base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33diff --git a/ui/android/.gitignore b/ui/android/.gitignorenew file mode 100644index 0000000..8dc1c6f--- /dev/null+++ b/ui/android/.gitignore@@ -0,0 +1,17 @@+gradle-wrapper.jar+/.gradle+/captures/+/gradlew+/gradlew.bat+/local.properties+GeneratedPluginRegistrant.java+.cxx/++# Remember to never publicly share your keystore.+# See https://flutter.dev/to/reference-keystore+key.properties+**/*.keystore+**/*.jks++# Go 核心的 AAR 由 scripts/build-android.sh 生成+/app/libs/diff --git a/ui/android/app/build.gradle.kts b/ui/android/app/build.gradle.ktsnew file mode 100644index 0000000..92b87fe--- /dev/null+++ b/ui/android/app/build.gradle.kts@@ -0,0 +1,50 @@+plugins {+ id("com.android.application")+ // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.+ id("dev.flutter.flutter-gradle-plugin")+}++android {+ namespace = "com.pasteferry.app"+ // design/phone-sync.md 3.3.8 节:Android 10 起;target 36 不用申请 Android 17 的局域网权限+ compileSdk = 36+ ndkVersion = flutter.ndkVersion++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ defaultConfig {+ applicationId = "com.pasteferry.app"+ minSdk = 29+ targetSdk = 36+ versionCode = flutter.versionCode+ versionName = flutter.versionName+ // 只出 arm64,原因见 scripts/build-android.sh;x86_64 的模拟器经 ARM 转译运行+ ndk { abiFilters += listOf("arm64-v8a") }+ }++ buildTypes {+ release {+ // 发版签名密钥还没生成(phone-task.md C6),先用调试密钥,只给内测+ signingConfig = signingConfigs.getByName("debug")+ }+ }+}++kotlin {+ compilerOptions {+ jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17+ }+}++flutter {+ source = "../.."+}++dependencies {+ // Go 核心,由 scripts/build-android.sh 用 gomobile bind 生成,不进版本库+ implementation(files("libs/pasteferry-core.aar"))+ implementation("androidx.core:core-ktx:1.17.0")+}diff --git a/ui/android/app/src/debug/AndroidManifest.xml b/ui/android/app/src/debug/AndroidManifest.xmlnew file mode 100644index 0000000..399f698--- /dev/null+++ b/ui/android/app/src/debug/AndroidManifest.xml@@ -0,0 +1,7 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- The INTERNET permission is required for development. Specifically,+ the Flutter tool needs it to communicate with the running application+ to allow setting breakpoints, to provide hot reload, etc.+ -->+ <uses-permission android:name="android.permission.INTERNET"/>+</manifest>diff --git a/ui/android/app/src/main/AndroidManifest.xml b/ui/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..bc34339--- /dev/null+++ b/ui/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,77 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- design/phone-sync.md 3.3.5 节 -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+ <!-- 持有 MulticastLock 才收得到 mDNS 的组播包;也是 connectedDevice 前台服务的前提 -->+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+ <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />++ <application+ android:label="@string/app_name"+ android:name=".PasteFerryApp"+ android:icon="@mipmap/ic_launcher"+ android:allowBackup="false"+ android:fullBackupContent="false"+ android:dataExtractionRules="@xml/data_extraction_rules">+ <activity+ android:name=".MainActivity"+ android:exported="true"+ android:launchMode="singleTop"+ android:taskAffinity=""+ android:theme="@style/LaunchTheme"+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"+ android:hardwareAccelerated="true"+ android:windowSoftInputMode="adjustResize">+ <!-- Specifies an Android theme to apply to this Activity as soon as+ the Android process has started. This theme is visible to the user+ while the Flutter UI initializes. After that, this theme continues+ to determine the Window background behind the Flutter UI. -->+ <meta-data+ android:name="io.flutter.embedding.android.NormalTheme"+ android:resource="@style/NormalTheme"+ />+ <intent-filter>+ <action android:name="android.intent.action.MAIN"/>+ <category android:name="android.intent.category.LAUNCHER"/>+ </intent-filter>+ </activity>++ <!-- 后台保持连接:持有 Go 核心与常驻通知(3.3.3 节) -->+ <service+ android:name=".SyncService"+ android:exported="false"+ android:foregroundServiceType="connectedDevice" />++ <!-- 剪贴板里的图片、文件,以及「分享」,都经它给出 content:// 地址 -->+ <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="${applicationId}.files"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths" />+ </provider>++ <!-- Don't delete the meta-data below.+ This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->+ <meta-data+ android:name="flutterEmbedding"+ android:value="2" />+ </application>+ <!-- Required to query activities that can process text, see:+ https://developer.android.com/training/package-visibility and+ https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.++ In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->+ <queries>+ <intent>+ <action android:name="android.intent.action.PROCESS_TEXT"/>+ <data android:mimeType="text/plain"/>+ </intent>+ </queries>+</manifest>diff --git a/ui/android/app/src/main/kotlin/com/pasteferry/app/Core.kt b/ui/android/app/src/main/kotlin/com/pasteferry/app/Core.ktnew file mode 100644index 0000000..ef77c60--- /dev/null+++ b/ui/android/app/src/main/kotlin/com/pasteferry/app/Core.kt@@ -0,0 +1,132 @@+package com.pasteferry.app++import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import android.net.Uri+import android.net.wifi.WifiManager+import android.os.Build+import android.os.Handler+import android.os.Looper+import android.provider.Settings+import android.util.Log+import androidx.core.content.FileProvider+import com.pasteferry.core.mobile.Host+import com.pasteferry.core.mobile.Mobile+import java.io.File+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * App 进程里唯一的 Go 核心(design/phone-sync.md 3.3.1 节)。+ *+ * 界面(MainActivity)和前台服务(SyncService)都经它启停;Flutter 界面经本机 gRPC 连进 Go 核心,+ * 端口与 token 在数据目录的 daemon.json 里。+ */+object Core : Host {+ private const val TAG = "PasteFerry"++ private lateinit var app: Context+ private val main = Handler(Looper.getMainLooper())+ private var multicast: WifiManager.MulticastLock? = null++ /** 常驻通知的内容:在线设备名、最近收到的一条的来源与类型 */+ @Volatile var online: List<String> = emptyList(); private set+ @Volatile var lastFrom = ""; private set+ @Volatile var lastKind = ""; private set++ /** 状态变了,在主线程调用。SyncService 据此更新常驻通知 */+ var onStatus: (() -> Unit)? = null++ fun init(context: Context) {+ app = context.applicationContext+ }++ /** Go 核心的数据目录:App 私有目录,别的 App 读不到;FileProvider 也只开放这里(res/xml/file_paths.xml) */+ fun dataDir(context: Context = app): File = File(context.filesDir, "pasteferry")++ val running: Boolean get() = Mobile.running()++ @Synchronized+ fun start() {+ if (Mobile.running()) return+ // 没有它 Android 会丢掉组播包,mDNS 发现不了局域网里的电脑+ val wifi = app.getSystemService(WifiManager::class.java)+ multicast = wifi?.createMulticastLock("pasteferry")?.apply {+ setReferenceCounted(false)+ acquire()+ }+ Mobile.start(dataDir().path, deviceName(), versionName(), this)+ Log.i(TAG, "Go 核心已启动")+ }++ @Synchronized+ fun stop() {+ if (!Mobile.running()) return+ Mobile.stop()+ multicast?.release()+ multicast = null+ online = emptyList()+ Log.i(TAG, "Go 核心已停止")+ }++ /** 第一次运行时的设备名:用户在系统设置里起的名字,没有时用型号 */+ private fun deviceName(): String =+ Settings.Global.getString(app.contentResolver, Settings.Global.DEVICE_NAME)?.takeIf { it.isNotBlank() }+ ?: Build.MODEL++ private fun versionName(): String =+ app.packageManager.getPackageInfo(app.packageName, 0).versionName ?: "dev"++ fun uriFor(path: String): Uri =+ FileProvider.getUriForFile(app, "${app.packageName}.files", File(path))++ // ─────────────── Host:Go 核心回调 ───────────────++ /** Android 写剪贴板不需要焦点,App 在后台也能写;但要在主线程调用,这里等它写完再返回结果给 Go */+ override fun writeClipboard(kind: String, text: String, html: String, paths: String) {+ val clip = when (kind) {+ "text" -> ClipData.newPlainText(label(), text)+ "html" -> ClipData.newHtmlText(label(), text, html)+ "image", "files" -> {+ val uris = paths.split('\n').filter { it.isNotEmpty() }.map(::uriFor)+ require(uris.isNotEmpty()) { "没有文件" }+ val cr = app.contentResolver+ ClipData.newUri(cr, label(), uris.first()).apply {+ for (u in uris.drop(1)) addItem(cr, ClipData.Item(u))+ }+ }+ else -> throw IllegalArgumentException("不支持的类型 $kind")+ }+ onMain { app.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip) }+ }++ override fun statusChanged(online: String, lastFrom: String, lastKind: String) {+ this.online = online.split('\n').filter { it.isNotEmpty() }+ this.lastFrom = lastFrom+ this.lastKind = lastKind+ main.post { onStatus?.invoke() }+ }++ private fun label(): String = app.getString(R.string.app_name)++ private fun onMain(block: () -> Unit) {+ if (Looper.myLooper() == Looper.getMainLooper()) {+ block()+ return+ }+ var error: Throwable? = null+ val done = CountDownLatch(1)+ main.post {+ try {+ block()+ } catch (t: Throwable) {+ error = t+ } finally {+ done.countDown()+ }+ }+ if (!done.await(5, TimeUnit.SECONDS)) throw IllegalStateException("写剪贴板超时")+ error?.let { throw it }+ }+}diff --git a/ui/android/app/src/main/kotlin/com/pasteferry/app/MainActivity.kt b/ui/android/app/src/main/kotlin/com/pasteferry/app/MainActivity.ktnew file mode 100644index 0000000..320e7c9--- /dev/null+++ b/ui/android/app/src/main/kotlin/com/pasteferry/app/MainActivity.kt@@ -0,0 +1,217 @@+package com.pasteferry.app++import android.Manifest+import android.annotation.SuppressLint+import android.content.ContentValues+import android.content.Intent+import android.content.pm.PackageManager+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import android.net.Uri+import android.os.Build+import android.os.PowerManager+import android.provider.MediaStore+import android.provider.Settings+import android.webkit.MimeTypeMap+import androidx.core.app.NotificationManagerCompat+import io.flutter.embedding.android.FlutterActivity+import io.flutter.embedding.engine.FlutterEngine+import io.flutter.plugin.common.MethodCall+import io.flutter.plugin.common.MethodChannel+import java.io.File+import java.util.concurrent.Executors++/**+ * Flutter 界面。和 Dart 之间只有一个平台通道 pasteferry/host:启停 Go 核心、后台开关、保存与分享、权限。+ * 其余的(记录、发送、配对、设置)都由 Dart 经 gRPC 直接和 Go 核心说。+ */+class MainActivity : FlutterActivity() {+ private val io = Executors.newSingleThreadExecutor()+ private var pendingNotification: MethodChannel.Result? = null++ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {+ super.configureFlutterEngine(flutterEngine)+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "pasteferry/host")+ .setMethodCallHandler(::handle)+ }++ override fun onStart() {+ super.onStart()+ startCore()+ }++ override fun onStop() {+ super.onStop()+ // 关了「后台保持连接」:离开前台就断开,回来再连(3.2.5 节)+ if (!Prefs.keepAlive(this) && !isChangingConfigurations) Core.stop()+ }++ override fun onDestroy() {+ io.shutdown()+ super.onDestroy()+ }++ private fun startCore() {+ if (Prefs.keepAlive(this)) SyncService.start(this)+ // 前台服务的启动是异步的:界面这边先把核心拉起来,Dart 马上就能连+ Core.start()+ }++ private fun handle(call: MethodCall, result: MethodChannel.Result) {+ when (call.method) {+ "start" -> background(result) {+ startCore()+ mapOf("dataDir" to Core.dataDir().path)+ }+ "keepAlive" -> result.success(Prefs.keepAlive(this))+ "setKeepAlive" -> {+ val on = call.arguments as Boolean+ Prefs.setKeepAlive(this, on)+ if (on) SyncService.start(this) else SyncService.stop(this)+ result.success(on)+ }+ "save" -> background(result) { save(call.argument<List<String>>("paths")!!) }+ "share" -> {+ share(call.argument<List<String>>("paths")!!)+ result.success(null)+ }+ "notifications" -> result.success(notificationState())+ "requestNotifications" -> requestNotifications(result)+ "batteryUnrestricted" -> result.success(batteryUnrestricted())+ "requestBatteryUnrestricted" -> {+ requestBatteryUnrestricted()+ result.success(null)+ }+ "onLan" -> result.success(onLan())+ else -> result.notImplemented()+ }+ }++ private fun background(result: MethodChannel.Result, work: () -> Any?) {+ io.execute {+ try {+ val value = work()+ runOnUiThread { result.success(value) }+ } catch (e: Exception) {+ runOnUiThread { result.error("failed", e.message ?: e.toString(), null) }+ }+ }+ }++ // ─────────────── 保存与分享(3.3.3 节) ───────────────++ /** 图片存进相册的 Pictures/PasteFerry,其他文件存进「下载」的 PasteFerry 文件夹。Android 10 起不需要存储权限。返回存下的个数 */+ private fun save(paths: List<String>): Int {+ var n = 0+ for (path in paths) {+ val f = File(path)+ val files = if (f.isDirectory) f.walkTopDown().filter { it.isFile }.toList() else listOf(f)+ for (file in files) {+ val sub = if (f.isDirectory) file.parentFile!!.relativeTo(f.parentFile!!).path else ""+ saveOne(file, sub)+ n+++ }+ }+ return n+ }++ private fun saveOne(file: File, sub: String) {+ val mime = mimeOf(file)+ val image = mime.startsWith("image/")+ val collection = if (image) MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)+ else MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)+ val dir = (if (image) "Pictures/PasteFerry" else "Download/PasteFerry") + (if (sub.isEmpty()) "" else "/$sub")+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, file.name)+ put(MediaStore.MediaColumns.MIME_TYPE, mime)+ put(MediaStore.MediaColumns.RELATIVE_PATH, dir)+ put(MediaStore.MediaColumns.IS_PENDING, 1)+ }+ val uri = contentResolver.insert(collection, values) ?: throw IllegalStateException("无法保存 ${file.name}")+ try {+ contentResolver.openOutputStream(uri)!!.use { out -> file.inputStream().use { it.copyTo(out) } }+ contentResolver.update(uri, ContentValues().apply { put(MediaStore.MediaColumns.IS_PENDING, 0) }, null, null)+ } catch (e: Exception) {+ contentResolver.delete(uri, null, null)+ throw e+ }+ }++ private fun share(paths: List<String>) {+ val files = paths.map(::File).flatMap { if (it.isDirectory) it.walkTopDown().filter(File::isFile).toList() else listOf(it) }+ if (files.isEmpty()) return+ val uris = ArrayList<Uri>(files.map { Core.uriFor(it.path) })+ val mimes = files.map(::mimeOf).distinct()+ val type = mimes.singleOrNull() ?: if (mimes.all { it.startsWith("image/") }) "image/*" else "*/*"+ val send = if (uris.size == 1) {+ Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_STREAM, uris.first())+ } else {+ Intent(Intent.ACTION_SEND_MULTIPLE).putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris)+ }+ send.setType(type).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+ startActivity(Intent.createChooser(send, getString(R.string.share_title)))+ }++ private fun mimeOf(f: File): String =+ MimeTypeMap.getSingleton().getMimeTypeFromExtension(f.extension.lowercase()) ?: "application/octet-stream"++ // ─────────────── 权限与系统设置 ───────────────++ /** granted、denied(可以再请求)或 blocked(只能去系统设置里打开) */+ private fun notificationState(): String {+ if (NotificationManagerCompat.from(this).areNotificationsEnabled()) return "granted"+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return "blocked"+ return if (getSharedPreferences("pasteferry", MODE_PRIVATE).getBoolean("asked_notifications", false) &&+ !shouldShowRequestPermissionRationale(Manifest.permission.POST_NOTIFICATIONS)+ ) "blocked" else "denied"+ }++ private fun requestNotifications(result: MethodChannel.Result) {+ val state = notificationState()+ if (state == "granted") return result.success(state)+ if (state == "blocked" || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {+ startActivity(+ Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).putExtra(Settings.EXTRA_APP_PACKAGE, packageName),+ )+ return result.success(state)+ }+ pendingNotification?.success(state)+ pendingNotification = result+ getSharedPreferences("pasteferry", MODE_PRIVATE).edit().putBoolean("asked_notifications", true).apply()+ requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)+ }++ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {+ super.onRequestPermissionsResult(requestCode, permissions, grantResults)+ if (requestCode != REQUEST_NOTIFICATIONS) return+ pendingNotification?.success(notificationState())+ pendingNotification = null+ // 授权之后常驻通知才显示出来:重新发一次+ if (Prefs.keepAlive(this) && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) SyncService.start(this)+ }++ private fun batteryUnrestricted(): Boolean =+ getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(packageName)++ @SuppressLint("BatteryLife")+ private fun requestBatteryUnrestricted() {+ // App 不经 Google Play 分发,可以直接弹出系统的确认框;有的国内系统不认这个动作,退回设置列表+ try {+ startActivity(Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:$packageName")))+ } catch (_: Exception) {+ startActivity(Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS))+ }+ }++ /** 当前网络是 Wi-Fi 或有线网:一期只在局域网里同步,不在时界面上提示 */+ private fun onLan(): Boolean {+ val cm = getSystemService(ConnectivityManager::class.java)+ val caps = cm.getNetworkCapabilities(cm.activeNetwork) ?: return false+ return caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||+ caps.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)+ }++ companion object {+ private const val REQUEST_NOTIFICATIONS = 1+ }+}diff --git a/ui/android/app/src/main/kotlin/com/pasteferry/app/PasteFerryApp.kt b/ui/android/app/src/main/kotlin/com/pasteferry/app/PasteFerryApp.ktnew file mode 100644index 0000000..cd3aee5--- /dev/null+++ b/ui/android/app/src/main/kotlin/com/pasteferry/app/PasteFerryApp.kt@@ -0,0 +1,24 @@+package com.pasteferry.app++import android.app.Application+import android.content.Context++class PasteFerryApp : Application() {+ override fun onCreate() {+ super.onCreate()+ Core.init(this)+ }+}++/** 「后台保持连接」开关(design/phone-sync.md 3.2.5 节),默认开。存在宿主这边:Go 核心没启动时也要读它 */+object Prefs {+ private const val FILE = "pasteferry"+ private const val KEEP_ALIVE = "keep_alive"++ fun keepAlive(c: Context): Boolean =+ c.getSharedPreferences(FILE, Context.MODE_PRIVATE).getBoolean(KEEP_ALIVE, true)++ fun setKeepAlive(c: Context, on: Boolean) {+ c.getSharedPreferences(FILE, Context.MODE_PRIVATE).edit().putBoolean(KEEP_ALIVE, on).apply()+ }+}diff --git a/ui/android/app/src/main/kotlin/com/pasteferry/app/SyncService.kt b/ui/android/app/src/main/kotlin/com/pasteferry/app/SyncService.ktnew file mode 100644index 0000000..34df742--- /dev/null+++ b/ui/android/app/src/main/kotlin/com/pasteferry/app/SyncService.kt@@ -0,0 +1,94 @@+package com.pasteferry.app++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.ServiceCompat+import androidx.core.content.ContextCompat++/**+ * 后台保持连接(design/phone-sync.md 3.3.3 节):connectedDevice 类型的前台服务,持有 Go 核心与一条常驻通知。+ * 没有 dataSync 那样每天限时的规定。通知只写连接状态和最近一条的来源与类型,不写正文。+ */+class SyncService : Service() {+ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ createChannel()+ ServiceCompat.startForeground(+ this, NOTIFICATION_ID, build(), ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE,+ )+ try {+ Core.start()+ } catch (e: Exception) {+ Log.e("PasteFerry", "后台服务启动 Go 核心失败", e)+ }+ Core.onStatus = { update() }+ return START_STICKY+ }++ override fun onDestroy() {+ Core.onStatus = null+ super.onDestroy()+ }++ private fun update() {+ getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, build())+ }++ private fun build(): Notification {+ val online = Core.online+ val title = if (online.isEmpty()) getString(R.string.notif_none)+ else getString(R.string.notif_online, online.joinToString("、"))+ val from = Core.lastFrom+ val text = if (from.isEmpty()) null else when (Core.lastKind) {+ "image" -> getString(R.string.notif_last_image, from)+ "file" -> getString(R.string.notif_last_file, from)+ else -> getString(R.string.notif_last_text, from)+ }+ val open = PendingIntent.getActivity(+ this, 0,+ Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),+ PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+ )+ return NotificationCompat.Builder(this, CHANNEL)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(title)+ .setContentText(text)+ .setContentIntent(open)+ .setOngoing(true)+ .setOnlyAlertOnce(true)+ .setShowWhen(false)+ .setSilent(true)+ .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)+ .build()+ }++ private fun createChannel() {+ val channel = NotificationChannel(CHANNEL, getString(R.string.channel_sync), NotificationManager.IMPORTANCE_LOW)+ channel.description = getString(R.string.channel_sync_desc)+ channel.setShowBadge(false)+ getSystemService(NotificationManager::class.java).createNotificationChannel(channel)+ }++ companion object {+ private const val CHANNEL = "sync"+ private const val NOTIFICATION_ID = 1++ fun start(c: Context) {+ ContextCompat.startForegroundService(c, Intent(c, SyncService::class.java))+ }++ fun stop(c: Context) {+ c.stopService(Intent(c, SyncService::class.java))+ }+ }+}diff --git a/ui/android/app/src/main/res/drawable-v21/launch_background.xml b/ui/android/app/src/main/res/drawable-v21/launch_background.xmlnew file mode 100644index 0000000..f74085f--- /dev/null+++ b/ui/android/app/src/main/res/drawable-v21/launch_background.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Modify this file to customize your launch splash screen -->+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:drawable="?android:colorBackground" />++ <!-- You can insert your own image assets here -->+ <!-- <item>+ <bitmap+ android:gravity="center"+ android:src="@mipmap/launch_image" />+ </item> -->+</layer-list>diff --git a/ui/android/app/src/main/res/drawable/ic_notification.xml b/ui/android/app/src/main/res/drawable/ic_notification.xmlnew file mode 100644index 0000000..98b7ed7--- /dev/null+++ b/ui/android/app/src/main/res/drawable/ic_notification.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- 常驻通知的小图标:单色剪贴板 -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M19,2h-4.18C14.4,0.84 13.3,0 12,0c-1.3,0 -2.4,0.84 -2.82,2L5,2c-1.1,0 -2,0.9 -2,2v16c0,1.1 0.9,2 2,2h14c1.1,0 2,-0.9 2,-2L21,4c0,-1.1 -0.9,-2 -2,-2zM12,2c0.55,0 1,0.45 1,1s-0.45,1 -1,1 -1,-0.45 -1,-1 0.45,-1 1,-1zM19,20L5,20L5,4h2v3h10L17,4h2v16z" />+</vector>diff --git a/ui/android/app/src/main/res/drawable/launch_background.xml b/ui/android/app/src/main/res/drawable/launch_background.xmlnew file mode 100644index 0000000..304732f--- /dev/null+++ b/ui/android/app/src/main/res/drawable/launch_background.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Modify this file to customize your launch splash screen -->+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">+ <item android:drawable="@android:color/white" />++ <!-- You can insert your own image assets here -->+ <!-- <item>+ <bitmap+ android:gravity="center"+ android:src="@mipmap/launch_image" />+ </item> -->+</layer-list>diff --git a/ui/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/ui/android/app/src/main/res/mipmap-hdpi/ic_launcher.pngnew file mode 100644index 0000000..96f0cccBinary files /dev/null and b/ui/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differdiff --git a/ui/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/ui/android/app/src/main/res/mipmap-mdpi/ic_launcher.pngnew file mode 100644index 0000000..e1a490eBinary files /dev/null and b/ui/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differdiff --git a/ui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/ui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.pngnew file mode 100644index 0000000..ae18406Binary files /dev/null and b/ui/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differdiff --git a/ui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/ui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.pngnew file mode 100644index 0000000..7350fcfBinary files /dev/null and b/ui/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differdiff --git a/ui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/ui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngnew file mode 100644index 0000000..1c85953Binary files /dev/null and b/ui/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differdiff --git a/ui/android/app/src/main/res/values-ja/strings.xml b/ui/android/app/src/main/res/values-ja/strings.xmlnew file mode 100644index 0000000..bfe4d4b--- /dev/null+++ b/ui/android/app/src/main/res/values-ja/strings.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">PasteFerry</string>+ <string name="channel_sync">バックグラウンド接続</string>+ <string name="channel_sync_desc">PasteFerry の接続を保ち、パソコンでコピーしたテキストをこのスマホで受け取れるようにします。</string>+ <string name="notif_online">%1$s に接続中</string>+ <string name="notif_none">オンラインのデバイスはありません</string>+ <string name="notif_last_text">最新:%1$s からのテキスト</string>+ <string name="notif_last_image">最新:%1$s からの画像</string>+ <string name="notif_last_file">最新:%1$s からのファイル</string>+ <string name="share_title">共有</string>+</resources>diff --git a/ui/android/app/src/main/res/values-night/styles.xml b/ui/android/app/src/main/res/values-night/styles.xmlnew file mode 100644index 0000000..06952be--- /dev/null+++ b/ui/android/app/src/main/res/values-night/styles.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->+ <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">+ <!-- Show a splash screen on the activity. Automatically removed when+ the Flutter engine draws its first frame -->+ <item name="android:windowBackground">@drawable/launch_background</item>+ </style>+ <!-- Theme applied to the Android Window as soon as the process has started.+ This theme determines the color of the Android Window while your+ Flutter UI initializes, as well as behind your Flutter UI while its+ running.++ This Theme is only used starting with V2 of Flutter's Android embedding. -->+ <style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">+ <item name="android:windowBackground">?android:colorBackground</item>+ </style>+</resources>diff --git a/ui/android/app/src/main/res/values-zh-rHK/strings.xml b/ui/android/app/src/main/res/values-zh-rHK/strings.xmlnew file mode 100644index 0000000..cd70da2--- /dev/null+++ b/ui/android/app/src/main/res/values-zh-rHK/strings.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">隔空貼</string>+ <string name="channel_sync">背景保持連線</string>+ <string name="channel_sync_desc">讓隔空貼保持連線,電腦上複製的文字能隨時到這支手機。</string>+ <string name="notif_online">已連線 %1$s</string>+ <string name="notif_none">沒有在線的裝置</string>+ <string name="notif_last_text">最近:來自 %1$s 的文字</string>+ <string name="notif_last_image">最近:來自 %1$s 的圖片</string>+ <string name="notif_last_file">最近:來自 %1$s 的檔案</string>+ <string name="share_title">分享</string>+</resources>diff --git a/ui/android/app/src/main/res/values-zh-rTW/strings.xml b/ui/android/app/src/main/res/values-zh-rTW/strings.xmlnew file mode 100644index 0000000..cd70da2--- /dev/null+++ b/ui/android/app/src/main/res/values-zh-rTW/strings.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">隔空貼</string>+ <string name="channel_sync">背景保持連線</string>+ <string name="channel_sync_desc">讓隔空貼保持連線,電腦上複製的文字能隨時到這支手機。</string>+ <string name="notif_online">已連線 %1$s</string>+ <string name="notif_none">沒有在線的裝置</string>+ <string name="notif_last_text">最近:來自 %1$s 的文字</string>+ <string name="notif_last_image">最近:來自 %1$s 的圖片</string>+ <string name="notif_last_file">最近:來自 %1$s 的檔案</string>+ <string name="share_title">分享</string>+</resources>diff --git a/ui/android/app/src/main/res/values-zh/strings.xml b/ui/android/app/src/main/res/values-zh/strings.xmlnew file mode 100644index 0000000..219d5e3--- /dev/null+++ b/ui/android/app/src/main/res/values-zh/strings.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">隔空贴</string>+ <string name="channel_sync">后台保持连接</string>+ <string name="channel_sync_desc">让隔空贴保持连接,电脑上复制的文字能随时到这台手机。</string>+ <string name="notif_online">已连接 %1$s</string>+ <string name="notif_none">没有在线的设备</string>+ <string name="notif_last_text">最近:来自 %1$s 的文字</string>+ <string name="notif_last_image">最近:来自 %1$s 的图片</string>+ <string name="notif_last_file">最近:来自 %1$s 的文件</string>+ <string name="share_title">分享</string>+</resources>diff --git a/ui/android/app/src/main/res/values/strings.xml b/ui/android/app/src/main/res/values/strings.xmlnew file mode 100644index 0000000..9ec1484--- /dev/null+++ b/ui/android/app/src/main/res/values/strings.xml@@ -0,0 +1,12 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">PasteFerry</string>+ <string name="channel_sync">Background connection</string>+ <string name="channel_sync_desc">Keeps PasteFerry connected so text copied on your computer reaches this phone.</string>+ <string name="notif_online">Connected to %1$s</string>+ <string name="notif_none">No devices online</string>+ <string name="notif_last_text">Latest: text from %1$s</string>+ <string name="notif_last_image">Latest: image from %1$s</string>+ <string name="notif_last_file">Latest: file from %1$s</string>+ <string name="share_title">Share</string>+</resources>diff --git a/ui/android/app/src/main/res/values/styles.xml b/ui/android/app/src/main/res/values/styles.xmlnew file mode 100644index 0000000..cb1ef88--- /dev/null+++ b/ui/android/app/src/main/res/values/styles.xml@@ -0,0 +1,18 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->+ <style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">+ <!-- Show a splash screen on the activity. Automatically removed when+ the Flutter engine draws its first frame -->+ <item name="android:windowBackground">@drawable/launch_background</item>+ </style>+ <!-- Theme applied to the Android Window as soon as the process has started.+ This theme determines the color of the Android Window while your+ Flutter UI initializes, as well as behind your Flutter UI while its+ running.++ This Theme is only used starting with V2 of Flutter's Android embedding. -->+ <style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">+ <item name="android:windowBackground">?android:colorBackground</item>+ </style>+</resources>diff --git a/ui/android/app/src/main/res/xml/data_extraction_rules.xml b/ui/android/app/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000..8ac8e19--- /dev/null+++ b/ui/android/app/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- 数据目录里有设备私钥与配对关系,不参与云备份和设备迁移(design/phone-sync.md 3.3.2 节第 8 条) -->+<data-extraction-rules>+ <cloud-backup>+ <exclude domain="root" />+ <exclude domain="file" />+ <exclude domain="database" />+ <exclude domain="sharedpref" />+ </cloud-backup>+ <device-transfer>+ <exclude domain="root" />+ <exclude domain="file" />+ <exclude domain="database" />+ <exclude domain="sharedpref" />+ </device-transfer>+</data-extraction-rules>diff --git a/ui/android/app/src/main/res/xml/file_paths.xml b/ui/android/app/src/main/res/xml/file_paths.xmlnew file mode 100644index 0000000..786bfdd--- /dev/null+++ b/ui/android/app/src/main/res/xml/file_paths.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Go 核心的数据目录(缓存、收藏、剪贴板图片都在里面),见 Core.dataDir -->+<paths>+ <files-path name="data" path="pasteferry/" />+</paths>diff --git a/ui/android/app/src/profile/AndroidManifest.xml b/ui/android/app/src/profile/AndroidManifest.xmlnew file mode 100644index 0000000..399f698--- /dev/null+++ b/ui/android/app/src/profile/AndroidManifest.xml@@ -0,0 +1,7 @@+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <!-- The INTERNET permission is required for development. Specifically,+ the Flutter tool needs it to communicate with the running application+ to allow setting breakpoints, to provide hot reload, etc.+ -->+ <uses-permission android:name="android.permission.INTERNET"/>+</manifest>diff --git a/ui/android/build.gradle.kts b/ui/android/build.gradle.ktsnew file mode 100644index 0000000..dbee657--- /dev/null+++ b/ui/android/build.gradle.kts@@ -0,0 +1,24 @@+allprojects {+ repositories {+ google()+ mavenCentral()+ }+}++val newBuildDir: Directory =+ rootProject.layout.buildDirectory+ .dir("../../build")+ .get()+rootProject.layout.buildDirectory.value(newBuildDir)++subprojects {+ val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)+ project.layout.buildDirectory.value(newSubprojectBuildDir)+}+subprojects {+ project.evaluationDependsOn(":app")+}++tasks.register<Delete>("clean") {+ delete(rootProject.layout.buildDirectory)+}diff --git a/ui/android/gradle.properties b/ui/android/gradle.propertiesnew file mode 100644index 0000000..e96108c--- /dev/null+++ b/ui/android/gradle.properties@@ -0,0 +1,6 @@+org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError+android.useAndroidX=true+# This newDsl flag was added by the Flutter template+android.newDsl=false+# This builtInKotlin flag was added by the Flutter template+android.builtInKotlin=falsediff --git a/ui/android/gradle/wrapper/gradle-wrapper.properties b/ui/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 0000000..167dcad--- /dev/null+++ b/ui/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,5 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zipdiff --git a/ui/android/settings.gradle.kts b/ui/android/settings.gradle.ktsnew file mode 100644index 0000000..c21f0c5--- /dev/null+++ b/ui/android/settings.gradle.kts@@ -0,0 +1,26 @@+pluginManagement {+ val flutterSdkPath =+ run {+ val properties = java.util.Properties()+ file("local.properties").inputStream().use { properties.load(it) }+ val flutterSdkPath = properties.getProperty("flutter.sdk")+ require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }+ flutterSdkPath+ }++ includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")++ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}++plugins {+ id("dev.flutter.flutter-plugin-loader") version "1.0.0"+ id("com.android.application") version "9.0.1" apply false+ id("org.jetbrains.kotlin.android") version "2.3.20" apply false+}++include(":app")diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dartindex 9db460f..bb526d9 100644--- a/ui/lib/app_state.dart+++ b/ui/lib/app_state.dart@@ -115,6 +115,10 @@ class AppState extends ChangeNotifier implements RecordDetails {List<Friend> _friends = const [];Profile? _profile;+ // 手机网页传输(design/phone-sync.md 第 2 节);旧版后台服务没有时为 null+ WebShareStatus? _webShare;+ final _webShareInviteUsed = StreamController<String>.broadcast();+/// 有人兑换了本机的好友码,等用户确认;非空时界面弹出确认框FriendRequest? _pendingFriend;final Set<String> _handledFriendSessions = {};@@ -248,6 +252,11 @@ class AppState extends ChangeNotifier implements RecordDetails {List<Friend> get friends => List.unmodifiable(_friends);Friend? friendById(String id) => _friends.where((f) => f.id == id).firstOrNull;Profile? get profile => _profile;++ WebShareStatus? get webShare => _webShare;++ /// 二维码刚被手机扫码用掉:二维码窗口据此换一张新的+ Stream<String> get webShareInviteUsed => _webShareInviteUsed.stream;FriendRequest? get pendingFriendRequest => _pendingFriend;bool friendCancelled(String deviceId) => _friendCancelled.contains(deviceId);@@ -346,6 +355,7 @@ class AppState extends ChangeNotifier implements RecordDetails {@overridevoid dispose() {_retry?.cancel();+ _webShareInviteUsed.close();_historySearch.dispose();_favoriteSearch.dispose();_events?.cancel();@@ -396,6 +406,7 @@ class AppState extends ChangeNotifier implements RecordDetails {await _loadDevices();await _loadFriends();+ await _loadWebShare();await _loadTransfers();await refreshNotificationStatus();@@ -539,7 +550,9 @@ class AppState extends ChangeNotifier implements RecordDetails {List<Friend> friends = const [],Profile? profile,FriendRequest? pendingFriend,+ WebShareStatus? webShare,}) {+ _webShare = webShare;_friends = friends;_profile = profile;_pendingFriend = pendingFriend;@@ -602,6 +615,41 @@ class AppState extends ChangeNotifier implements RecordDetails {}}+ Future<void> _loadWebShare() async {+ final conn = _conn;+ if (conn == null) return;+ try {+ _webShare = await conn.client.getWebShare(Empty());+ } on GrpcError {+ _webShare = null; // 旧版后台服务没有手机网页传输+ }+ }++ // ─────────────────────────── 手机网页传输 ───────────────────────────++ Future<void> setWebShare(bool enabled) async {+ _webShare = await _client.setWebShare(SetWebShareRequest(enabled: enabled));+ notifyListeners();+ }++ /// 生成一张新的二维码;[address] 为空时用默认地址+ Future<WebShareInvite> newWebShareInvite(String address) =>+ _client.newWebShareInvite(NewWebShareInviteRequest(address: address));++ /// 二维码窗口关闭:作废还没被用过的二维码+ Future<void> closeWebShareInvite(String id) async {+ try {+ await _client.closeWebShareInvite(WebShareInviteRef(id: id));+ } catch (_) {+ // 后台服务已经退出时它本来就作废了+ }+ }++ Future<void> removeWebSession(String id) async {+ _webShare = await _client.removeWebSession(WebSessionRef(id: id));+ notifyListeners();+ }+Future<void> _loadFriends() async {final conn = _conn;if (conn == null) return;@@ -721,6 +769,12 @@ class AppState extends ChangeNotifier implements RecordDetails {case Event_Payload.profileChanged:_profile = ev.profileChanged;+ case Event_Payload.webShareChanged:+ _webShare = ev.webShareChanged;+ if (ev.webShareChanged.inviteUsed.isNotEmpty) {+ _webShareInviteUsed.add(ev.webShareChanged.inviteUsed);+ }+default:break;}@@ -1219,6 +1273,9 @@ class AppState extends ChangeNotifier implements RecordDetails {return d;}+ /// 图片和文件在本机的路径(Android 的「保存」「分享」用);不在本机时为空。下载后会变,不缓存+ Future<List<String>> localPaths(String clipId) async => (await requestClipDetail(clipId)).localPaths;+@protectedFuture<ClipDetail> requestClipDetail(String clipId) =>_client.getClipDetail(GetClipDetailRequest(clipId: clipId));@@ -1296,6 +1353,14 @@ class AppState extends ChangeNotifier implements RecordDetails {Future<void> applyToClipboard(String clipId) =>_client.applyToClipboard(ApplyToClipboardRequest(clipId: clipId));+ /// 手机发送页:把文字当成本机复制,进记录并发给在线的设备,不写手机自己的剪贴板(design/phone-sync.md 3.2.3 节)+ Future<ClipRecord> submitText(String text) async {+ final r = await _client.submitText(SubmitTextRequest(text: text));+ _upsert(r);+ notifyListeners();+ return r;+ }+/// 一条记录里第 [index] 张图片:本机路径、文件名,以及能预览的图片总数。/// HEIC 这类格式由后台服务先转换,大图可能要一两秒,超时放宽一些。@overridediff --git a/ui/lib/daemon_client.dart b/ui/lib/daemon_client.dartindex d511501..6160892 100644--- a/ui/lib/daemon_client.dart+++ b/ui/lib/daemon_client.dart@@ -37,6 +37,9 @@ class DaemonEndpoint {/// `~/Library/Application Support/<bundle_id>`,与 daemon 用的/// `~/Library/Application Support/PasteFerry` 并不是同一个位置。static String defaultDataDir() {+ // Android:Go 核心跑在 App 进程里,数据目录由 Kotlin 宿主给出(mobile/host.dart)+ final android = androidDataDir;+ if (android != null) return android;if (Platform.isMacOS) {final home = Platform.environment['HOME'] ?? '';return '$home/Library/Application Support/PasteFerry';@@ -54,6 +57,9 @@ class DaemonEndpoint {return '$base/pasteferry';}+ /// Android 上 App 私有目录里的数据目录,启动时由宿主设置。+ static String? androidDataDir;+static File endpointFile([String? dataDir]) =>File('${dataDir ?? defaultDataDir()}${Platform.pathSeparator}daemon.json');diff --git a/ui/lib/gen/pasteferry/v1/daemon.pb.dart b/ui/lib/gen/pasteferry/v1/daemon.pb.dartindex 2de688d..446d173 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pb.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pb.dart@@ -171,6 +171,7 @@ class ClipRecord extends $pb.GeneratedMessage {$fixnum.Int64? favoritedAtUnix,$core.bool? isLink,$core.String? alias,+ $core.String? viaName,}) {final result = ClipRecord._();if (id != null) result.id = id;@@ -191,6 +192,7 @@ class ClipRecord extends $pb.GeneratedMessage {if (favoritedAtUnix != null) result.favoritedAtUnix = favoritedAtUnix;if (isLink != null) result.isLink = isLink;if (alias != null) result.alias = alias;+ if (viaName != null) result.viaName = viaName;return result;}@@ -228,6 +230,7 @@ class ClipRecord extends $pb.GeneratedMessage {..aInt64(16, _omitFieldNames ? '' : 'favoritedAtUnix')..aOB(17, _omitFieldNames ? '' : 'isLink')..aOS(18, _omitFieldNames ? '' : 'alias')+ ..aOS(19, _omitFieldNames ? '' : 'viaName')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -411,6 +414,17 @@ class ClipRecord extends $pb.GeneratedMessage {$core.bool hasAlias() => $_has(17);@$pb.TagNumber(18)void clearAlias() => $_clearField(18);++ /// 经由哪台没配对的设备送进本机:手机网页传输里登记的手机名。只有 outgoing 的记录会有,+ /// 界面上显示「来自 via_name」而不是「本机」+ @$pb.TagNumber(19)+ $core.String get viaName => $_getSZ(18);+ @$pb.TagNumber(19)+ set viaName($core.String value) => $_setString(18, value);+ @$pb.TagNumber(19)+ $core.bool hasViaName() => $_has(18);+ @$pb.TagNumber(19)+ void clearViaName() => $_clearField(19);}class SubscribeRequest extends $pb.GeneratedMessage {@@ -792,6 +806,7 @@ enum Event_Payload {friendRemoved,friendRequest,profileChanged,+ webShareChanged,notSet}@@ -814,6 +829,7 @@ class Event extends $pb.GeneratedMessage {$core.String? friendRemoved,FriendRequest? friendRequest,Profile? profileChanged,+ WebShareStatus? webShareChanged,}) {final result = Event._();if (clipAdded != null) result.clipAdded = clipAdded;@@ -833,6 +849,7 @@ class Event extends $pb.GeneratedMessage {if (friendRemoved != null) result.friendRemoved = friendRemoved;if (friendRequest != null) result.friendRequest = friendRequest;if (profileChanged != null) result.profileChanged = profileChanged;+ if (webShareChanged != null) result.webShareChanged = webShareChanged;return result;}@@ -863,13 +880,14 @@ class Event extends $pb.GeneratedMessage {15: Event_Payload.friendRemoved,16: Event_Payload.friendRequest,17: Event_Payload.profileChanged,+ 18: Event_Payload.webShareChanged,0: Event_Payload.notSet};static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Event',package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),createEmptyInstance: Event.$_createMessage)- ..oo(0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])+ ..oo(0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])..aOM<ClipRecord>(1, _omitFieldNames ? '' : 'clipAdded',subBuilder: ClipRecord.$_createMessage)..aOM<ClipRecord>(2, _omitFieldNames ? '' : 'clipUpdated',@@ -900,6 +918,8 @@ class Event extends $pb.GeneratedMessage {subBuilder: FriendRequest.$_createMessage)..aOM<Profile>(17, _omitFieldNames ? '' : 'profileChanged',subBuilder: Profile.$_createMessage)+ ..aOM<WebShareStatus>(18, _omitFieldNames ? '' : 'webShareChanged',+ subBuilder: WebShareStatus.$_createMessage)..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -939,6 +959,7 @@ class Event extends $pb.GeneratedMessage {@$pb.TagNumber(15)@$pb.TagNumber(16)@$pb.TagNumber(17)+ @$pb.TagNumber(18)Event_Payload whichPayload() => _Event_PayloadByTag[$_whichOneof(0)]!;@$pb.TagNumber(1)@$pb.TagNumber(2)@@ -957,6 +978,7 @@ class Event extends $pb.GeneratedMessage {@$pb.TagNumber(15)@$pb.TagNumber(16)@$pb.TagNumber(17)+ @$pb.TagNumber(18)void clearPayload() => $_clearField($_whichOneof(0));@$pb.TagNumber(1)@@ -1141,6 +1163,18 @@ class Event extends $pb.GeneratedMessage {void clearProfileChanged() => $_clearField(17);@$pb.TagNumber(17)Profile ensureProfileChanged() => $_ensure(16);++ /// 手机网页传输的开关、监听状态或登记的手机变了;invite_used 是刚被扫码用掉的二维码+ @$pb.TagNumber(18)+ WebShareStatus get webShareChanged => $_getN(17);+ @$pb.TagNumber(18)+ set webShareChanged(WebShareStatus value) => $_setField(18, value);+ @$pb.TagNumber(18)+ $core.bool hasWebShareChanged() => $_has(17);+ @$pb.TagNumber(18)+ void clearWebShareChanged() => $_clearField(18);+ @$pb.TagNumber(18)+ WebShareStatus ensureWebShareChanged() => $_ensure(17);}class Profile extends $pb.GeneratedMessage {@@ -3156,11 +3190,13 @@ class ClipDetail extends $pb.GeneratedMessage {$core.String? text,$core.int? textLength,$core.Iterable<$core.String>? sourcePaths,+ $core.Iterable<$core.String>? localPaths,}) {final result = ClipDetail._();if (text != null) result.text = text;if (textLength != null) result.textLength = textLength;if (sourcePaths != null) result.sourcePaths.addAll(sourcePaths);+ if (localPaths != null) result.localPaths.addAll(localPaths);return result;}@@ -3180,6 +3216,7 @@ class ClipDetail extends $pb.GeneratedMessage {..aOS(1, _omitFieldNames ? '' : 'text')..aI(2, _omitFieldNames ? '' : 'textLength')..pPS(3, _omitFieldNames ? '' : 'sourcePaths')+ ..pPS(4, _omitFieldNames ? '' : 'localPaths')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -3225,6 +3262,11 @@ class ClipDetail extends $pb.GeneratedMessage {/// 本机复制的文件在本机的完整路径@$pb.TagNumber(3)$pb.PbList<$core.String> get sourcePaths => $_getList(2);++ /// 图片和文件已在本机时,内容在本机的路径(缓存或收藏目录里,或者本机复制的原文件)。+ /// Android 的「保存」「分享」用它;还没下载或已过期时为空+ @$pb.TagNumber(4)+ $pb.PbList<$core.String> get localPaths => $_getList(3);}class QuickPasteStatus extends $pb.GeneratedMessage {@@ -7409,6 +7451,627 @@ class CheckReceiveDirResponse extends $pb.GeneratedMessage {void clearPath() => $_clearField(4);}+class SubmitTextRequest extends $pb.GeneratedMessage {+ factory SubmitTextRequest({+ $core.String? text,+ }) {+ final result = SubmitTextRequest._();+ if (text != null) result.text = text;+ return result;+ }++ SubmitTextRequest._();++ factory SubmitTextRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SubmitTextRequest()..mergeFromBuffer(data, registry);+ factory SubmitTextRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SubmitTextRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SubmitTextRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: SubmitTextRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'text')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SubmitTextRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SubmitTextRequest copyWith(void Function(SubmitTextRequest) updates) =>+ super.copyWith((message) => updates(message as SubmitTextRequest))+ as SubmitTextRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SubmitTextRequest() / SubmitTextRequest.new instead')+ static SubmitTextRequest create() => SubmitTextRequest._();+ static $pb.GeneratedMessage $_createMessage() => SubmitTextRequest._();+ @$core.override+ SubmitTextRequest createEmptyInstance() => SubmitTextRequest._();+ @$core.pragma('dart2js:noInline')+ static SubmitTextRequest getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<SubmitTextRequest>(+ SubmitTextRequest.$_createMessage);+ static SubmitTextRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get text => $_getSZ(0);+ @$pb.TagNumber(1)+ set text($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasText() => $_has(0);+ @$pb.TagNumber(1)+ void clearText() => $_clearField(1);+}++class WebShareStatus extends $pb.GeneratedMessage {+ factory WebShareStatus({+ $core.bool? enabled,+ $core.bool? listening,+ $core.int? port,+ $core.bool? portFallback,+ $core.String? error,+ $core.Iterable<$core.String>? addresses,+ $core.Iterable<WebSession>? sessions,+ $core.String? inviteUsed,+ }) {+ final result = WebShareStatus._();+ if (enabled != null) result.enabled = enabled;+ if (listening != null) result.listening = listening;+ if (port != null) result.port = port;+ if (portFallback != null) result.portFallback = portFallback;+ if (error != null) result.error = error;+ if (addresses != null) result.addresses.addAll(addresses);+ if (sessions != null) result.sessions.addAll(sessions);+ if (inviteUsed != null) result.inviteUsed = inviteUsed;+ return result;+ }++ WebShareStatus._();++ factory WebShareStatus.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareStatus()..mergeFromBuffer(data, registry);+ factory WebShareStatus.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareStatus()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'WebShareStatus',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: WebShareStatus.$_createMessage)+ ..aOB(1, _omitFieldNames ? '' : 'enabled')+ ..aOB(2, _omitFieldNames ? '' : 'listening')+ ..aI(3, _omitFieldNames ? '' : 'port')+ ..aOB(4, _omitFieldNames ? '' : 'portFallback')+ ..aOS(5, _omitFieldNames ? '' : 'error')+ ..pPS(6, _omitFieldNames ? '' : 'addresses')+ ..pPM<WebSession>(7, _omitFieldNames ? '' : 'sessions',+ subBuilder: WebSession.$_createMessage)+ ..aOS(8, _omitFieldNames ? '' : 'inviteUsed')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareStatus clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareStatus copyWith(void Function(WebShareStatus) updates) =>+ super.copyWith((message) => updates(message as WebShareStatus))+ as WebShareStatus;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use WebShareStatus() / WebShareStatus.new instead')+ static WebShareStatus create() => WebShareStatus._();+ static $pb.GeneratedMessage $_createMessage() => WebShareStatus._();+ @$core.override+ WebShareStatus createEmptyInstance() => WebShareStatus._();+ @$core.pragma('dart2js:noInline')+ static WebShareStatus getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WebShareStatus>(+ WebShareStatus.$_createMessage);+ static WebShareStatus? _defaultInstance;++ @$pb.TagNumber(1)+ $core.bool get enabled => $_getBF(0);+ @$pb.TagNumber(1)+ set enabled($core.bool value) => $_setBool(0, value);+ @$pb.TagNumber(1)+ $core.bool hasEnabled() => $_has(0);+ @$pb.TagNumber(1)+ void clearEnabled() => $_clearField(1);++ /// 开关打开且端口已在监听+ @$pb.TagNumber(2)+ $core.bool get listening => $_getBF(1);+ @$pb.TagNumber(2)+ set listening($core.bool value) => $_setBool(1, value);+ @$pb.TagNumber(2)+ $core.bool hasListening() => $_has(1);+ @$pb.TagNumber(2)+ void clearListening() => $_clearField(2);++ @$pb.TagNumber(3)+ $core.int get port => $_getIZ(2);+ @$pb.TagNumber(3)+ set port($core.int value) => $_setSignedInt32(2, value);+ @$pb.TagNumber(3)+ $core.bool hasPort() => $_has(2);+ @$pb.TagNumber(3)+ void clearPort() => $_clearField(3);++ /// 固定端口被占用,改用了随机端口:以前收藏的网址打不开,要重新扫码+ @$pb.TagNumber(4)+ $core.bool get portFallback => $_getBF(3);+ @$pb.TagNumber(4)+ set portFallback($core.bool value) => $_setBool(3, value);+ @$pb.TagNumber(4)+ $core.bool hasPortFallback() => $_has(3);+ @$pb.TagNumber(4)+ void clearPortFallback() => $_clearField(4);++ /// 监听失败的原因(开关开着但没在监听时)+ @$pb.TagNumber(5)+ $core.String get error => $_getSZ(4);+ @$pb.TagNumber(5)+ set error($core.String value) => $_setString(4, value);+ @$pb.TagNumber(5)+ $core.bool hasError() => $_has(4);+ @$pb.TagNumber(5)+ void clearError() => $_clearField(5);++ /// 本机的局域网地址(不带端口),默认路由所在的网卡排第一+ @$pb.TagNumber(6)+ $pb.PbList<$core.String> get addresses => $_getList(5);++ @$pb.TagNumber(7)+ $pb.PbList<WebSession> get sessions => $_getList(6);++ /// 刚被扫码用掉的二维码(只在 web_share_changed 事件里有),二维码窗口据此换一张新的+ @$pb.TagNumber(8)+ $core.String get inviteUsed => $_getSZ(7);+ @$pb.TagNumber(8)+ set inviteUsed($core.String value) => $_setString(7, value);+ @$pb.TagNumber(8)+ $core.bool hasInviteUsed() => $_has(7);+ @$pb.TagNumber(8)+ void clearInviteUsed() => $_clearField(8);+}++class WebSession extends $pb.GeneratedMessage {+ factory WebSession({+ $core.String? id,+ $core.String? name,+ $fixnum.Int64? createdAtUnix,+ $fixnum.Int64? lastSeenUnix,+ }) {+ final result = WebSession._();+ if (id != null) result.id = id;+ if (name != null) result.name = name;+ if (createdAtUnix != null) result.createdAtUnix = createdAtUnix;+ if (lastSeenUnix != null) result.lastSeenUnix = lastSeenUnix;+ return result;+ }++ WebSession._();++ factory WebSession.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebSession()..mergeFromBuffer(data, registry);+ factory WebSession.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebSession()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'WebSession',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: WebSession.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..aOS(2, _omitFieldNames ? '' : 'name')+ ..aInt64(3, _omitFieldNames ? '' : 'createdAtUnix')+ ..aInt64(4, _omitFieldNames ? '' : 'lastSeenUnix')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebSession clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebSession copyWith(void Function(WebSession) updates) =>+ super.copyWith((message) => updates(message as WebSession)) as WebSession;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use WebSession() / WebSession.new instead')+ static WebSession create() => WebSession._();+ static $pb.GeneratedMessage $_createMessage() => WebSession._();+ @$core.override+ WebSession createEmptyInstance() => WebSession._();+ @$core.pragma('dart2js:noInline')+ static WebSession getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<WebSession>(WebSession.$_createMessage);+ static WebSession? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get name => $_getSZ(1);+ @$pb.TagNumber(2)+ set name($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasName() => $_has(1);+ @$pb.TagNumber(2)+ void clearName() => $_clearField(2);++ @$pb.TagNumber(3)+ $fixnum.Int64 get createdAtUnix => $_getI64(2);+ @$pb.TagNumber(3)+ set createdAtUnix($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasCreatedAtUnix() => $_has(2);+ @$pb.TagNumber(3)+ void clearCreatedAtUnix() => $_clearField(3);++ @$pb.TagNumber(4)+ $fixnum.Int64 get lastSeenUnix => $_getI64(3);+ @$pb.TagNumber(4)+ set lastSeenUnix($fixnum.Int64 value) => $_setInt64(3, value);+ @$pb.TagNumber(4)+ $core.bool hasLastSeenUnix() => $_has(3);+ @$pb.TagNumber(4)+ void clearLastSeenUnix() => $_clearField(4);+}++class SetWebShareRequest extends $pb.GeneratedMessage {+ factory SetWebShareRequest({+ $core.bool? enabled,+ }) {+ final result = SetWebShareRequest._();+ if (enabled != null) result.enabled = enabled;+ return result;+ }++ SetWebShareRequest._();++ factory SetWebShareRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SetWebShareRequest()..mergeFromBuffer(data, registry);+ factory SetWebShareRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ SetWebShareRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'SetWebShareRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: SetWebShareRequest.$_createMessage)+ ..aOB(1, _omitFieldNames ? '' : 'enabled')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SetWebShareRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ SetWebShareRequest copyWith(void Function(SetWebShareRequest) updates) =>+ super.copyWith((message) => updates(message as SetWebShareRequest))+ as SetWebShareRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use SetWebShareRequest() / SetWebShareRequest.new instead')+ static SetWebShareRequest create() => SetWebShareRequest._();+ static $pb.GeneratedMessage $_createMessage() => SetWebShareRequest._();+ @$core.override+ SetWebShareRequest createEmptyInstance() => SetWebShareRequest._();+ @$core.pragma('dart2js:noInline')+ static SetWebShareRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<SetWebShareRequest>(+ SetWebShareRequest.$_createMessage);+ static SetWebShareRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.bool get enabled => $_getBF(0);+ @$pb.TagNumber(1)+ set enabled($core.bool value) => $_setBool(0, value);+ @$pb.TagNumber(1)+ $core.bool hasEnabled() => $_has(0);+ @$pb.TagNumber(1)+ void clearEnabled() => $_clearField(1);+}++class NewWebShareInviteRequest extends $pb.GeneratedMessage {+ factory NewWebShareInviteRequest({+ $core.String? address,+ }) {+ final result = NewWebShareInviteRequest._();+ if (address != null) result.address = address;+ return result;+ }++ NewWebShareInviteRequest._();++ factory NewWebShareInviteRequest.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NewWebShareInviteRequest()..mergeFromBuffer(data, registry);+ factory NewWebShareInviteRequest.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ NewWebShareInviteRequest()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'NewWebShareInviteRequest',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: NewWebShareInviteRequest.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'address')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NewWebShareInviteRequest clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ NewWebShareInviteRequest copyWith(+ void Function(NewWebShareInviteRequest) updates) =>+ super.copyWith((message) => updates(message as NewWebShareInviteRequest))+ as NewWebShareInviteRequest;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated(+ 'Use NewWebShareInviteRequest() / NewWebShareInviteRequest.new instead')+ static NewWebShareInviteRequest create() => NewWebShareInviteRequest._();+ static $pb.GeneratedMessage $_createMessage() => NewWebShareInviteRequest._();+ @$core.override+ NewWebShareInviteRequest createEmptyInstance() =>+ NewWebShareInviteRequest._();+ @$core.pragma('dart2js:noInline')+ static NewWebShareInviteRequest getDefault() => _defaultInstance ??=+ $pb.GeneratedMessage.$_defaultFor<NewWebShareInviteRequest>(+ NewWebShareInviteRequest.$_createMessage);+ static NewWebShareInviteRequest? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get address => $_getSZ(0);+ @$pb.TagNumber(1)+ set address($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasAddress() => $_has(0);+ @$pb.TagNumber(1)+ void clearAddress() => $_clearField(1);+}++class WebShareInvite extends $pb.GeneratedMessage {+ factory WebShareInvite({+ $core.String? id,+ $core.String? url,+ $fixnum.Int64? expiresAtUnix,+ $core.int? qrSize,+ $core.List<$core.int>? qrModules,+ }) {+ final result = WebShareInvite._();+ if (id != null) result.id = id;+ if (url != null) result.url = url;+ if (expiresAtUnix != null) result.expiresAtUnix = expiresAtUnix;+ if (qrSize != null) result.qrSize = qrSize;+ if (qrModules != null) result.qrModules = qrModules;+ return result;+ }++ WebShareInvite._();++ factory WebShareInvite.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareInvite()..mergeFromBuffer(data, registry);+ factory WebShareInvite.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareInvite()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'WebShareInvite',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: WebShareInvite.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..aOS(2, _omitFieldNames ? '' : 'url')+ ..aInt64(3, _omitFieldNames ? '' : 'expiresAtUnix')+ ..aI(4, _omitFieldNames ? '' : 'qrSize')+ ..a<$core.List<$core.int>>(+ 5, _omitFieldNames ? '' : 'qrModules', $pb.PbFieldType.OY)+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareInvite clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareInvite copyWith(void Function(WebShareInvite) updates) =>+ super.copyWith((message) => updates(message as WebShareInvite))+ as WebShareInvite;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use WebShareInvite() / WebShareInvite.new instead')+ static WebShareInvite create() => WebShareInvite._();+ static $pb.GeneratedMessage $_createMessage() => WebShareInvite._();+ @$core.override+ WebShareInvite createEmptyInstance() => WebShareInvite._();+ @$core.pragma('dart2js:noInline')+ static WebShareInvite getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WebShareInvite>(+ WebShareInvite.$_createMessage);+ static WebShareInvite? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);++ @$pb.TagNumber(2)+ $core.String get url => $_getSZ(1);+ @$pb.TagNumber(2)+ set url($core.String value) => $_setString(1, value);+ @$pb.TagNumber(2)+ $core.bool hasUrl() => $_has(1);+ @$pb.TagNumber(2)+ void clearUrl() => $_clearField(2);++ @$pb.TagNumber(3)+ $fixnum.Int64 get expiresAtUnix => $_getI64(2);+ @$pb.TagNumber(3)+ set expiresAtUnix($fixnum.Int64 value) => $_setInt64(2, value);+ @$pb.TagNumber(3)+ $core.bool hasExpiresAtUnix() => $_has(2);+ @$pb.TagNumber(3)+ void clearExpiresAtUnix() => $_clearField(3);++ /// 二维码点阵,界面按它画方块:边长(模块数)与按行排列的模块,每个字节一个,1 为深色+ @$pb.TagNumber(4)+ $core.int get qrSize => $_getIZ(3);+ @$pb.TagNumber(4)+ set qrSize($core.int value) => $_setSignedInt32(3, value);+ @$pb.TagNumber(4)+ $core.bool hasQrSize() => $_has(3);+ @$pb.TagNumber(4)+ void clearQrSize() => $_clearField(4);++ @$pb.TagNumber(5)+ $core.List<$core.int> get qrModules => $_getN(4);+ @$pb.TagNumber(5)+ set qrModules($core.List<$core.int> value) => $_setBytes(4, value);+ @$pb.TagNumber(5)+ $core.bool hasQrModules() => $_has(4);+ @$pb.TagNumber(5)+ void clearQrModules() => $_clearField(5);+}++class WebShareInviteRef extends $pb.GeneratedMessage {+ factory WebShareInviteRef({+ $core.String? id,+ }) {+ final result = WebShareInviteRef._();+ if (id != null) result.id = id;+ return result;+ }++ WebShareInviteRef._();++ factory WebShareInviteRef.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareInviteRef()..mergeFromBuffer(data, registry);+ factory WebShareInviteRef.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebShareInviteRef()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'WebShareInviteRef',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: WebShareInviteRef.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareInviteRef clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebShareInviteRef copyWith(void Function(WebShareInviteRef) updates) =>+ super.copyWith((message) => updates(message as WebShareInviteRef))+ as WebShareInviteRef;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use WebShareInviteRef() / WebShareInviteRef.new instead')+ static WebShareInviteRef create() => WebShareInviteRef._();+ static $pb.GeneratedMessage $_createMessage() => WebShareInviteRef._();+ @$core.override+ WebShareInviteRef createEmptyInstance() => WebShareInviteRef._();+ @$core.pragma('dart2js:noInline')+ static WebShareInviteRef getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WebShareInviteRef>(+ WebShareInviteRef.$_createMessage);+ static WebShareInviteRef? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);+}++class WebSessionRef extends $pb.GeneratedMessage {+ factory WebSessionRef({+ $core.String? id,+ }) {+ final result = WebSessionRef._();+ if (id != null) result.id = id;+ return result;+ }++ WebSessionRef._();++ factory WebSessionRef.fromBuffer($core.List<$core.int> data,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebSessionRef()..mergeFromBuffer(data, registry);+ factory WebSessionRef.fromJson($core.String json,+ [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) =>+ WebSessionRef()..mergeFromJson(json, registry);++ static final $pb.BuilderInfo _i = $pb.BuilderInfo(+ _omitMessageNames ? '' : 'WebSessionRef',+ package: const $pb.PackageName(_omitMessageNames ? '' : 'pasteferry.v1'),+ createEmptyInstance: WebSessionRef.$_createMessage)+ ..aOS(1, _omitFieldNames ? '' : 'id')+ ..hasRequiredFields = false;++ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebSessionRef clone() => deepCopy();+ @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')+ WebSessionRef copyWith(void Function(WebSessionRef) updates) =>+ super.copyWith((message) => updates(message as WebSessionRef))+ as WebSessionRef;++ @$core.override+ $pb.BuilderInfo get info_ => _i;++ @$core.pragma('dart2js:noInline')+ @$core.Deprecated('Use WebSessionRef() / WebSessionRef.new instead')+ static WebSessionRef create() => WebSessionRef._();+ static $pb.GeneratedMessage $_createMessage() => WebSessionRef._();+ @$core.override+ WebSessionRef createEmptyInstance() => WebSessionRef._();+ @$core.pragma('dart2js:noInline')+ static WebSessionRef getDefault() =>+ _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<WebSessionRef>(+ WebSessionRef.$_createMessage);+ static WebSessionRef? _defaultInstance;++ @$pb.TagNumber(1)+ $core.String get id => $_getSZ(0);+ @$pb.TagNumber(1)+ set id($core.String value) => $_setString(0, value);+ @$pb.TagNumber(1)+ $core.bool hasId() => $_has(0);+ @$pb.TagNumber(1)+ void clearId() => $_clearField(1);+}+const $core.bool _omitFieldNames =$core.bool.fromEnvironment('protobuf.omit_field_names');const $core.bool _omitMessageNames =diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dartindex 7eda2fa..33195b3 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbgrpc.dart@@ -474,6 +474,54 @@ class DaemonServiceClient extends $grpc.Client {return $createUnaryCall(_$blockDevice, request, options: options);}+ /// 发送页里输入的文字:当成本机复制,落库并发给其他设备,不写本机剪贴板(Android App,design/phone-sync.md 3.3.2 节)+ $grpc.ResponseFuture<$0.ClipRecord> submitText(+ $0.SubmitTextRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$submitText, request, options: options);+ }++ /// 手机网页传输(design/phone-sync.md 第 2 节):手机扫码后用浏览器和本机互传+ $grpc.ResponseFuture<$0.WebShareStatus> getWebShare(+ $0.Empty request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$getWebShare, request, options: options);+ }++ /// 打开或关闭总开关。关闭时停止监听端口,已登记的手机保留+ $grpc.ResponseFuture<$0.WebShareStatus> setWebShare(+ $0.SetWebShareRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$setWebShare, request, options: options);+ }++ /// 二维码窗口打开、或上一个二维码被用掉 / 过期时调用:生成一个待用的会话,返回二维码里的网址+ $grpc.ResponseFuture<$0.WebShareInvite> newWebShareInvite(+ $0.NewWebShareInviteRequest request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$newWebShareInvite, request, options: options);+ }++ /// 二维码窗口关闭:作废还没被用过的二维码+ $grpc.ResponseFuture<$0.Empty> closeWebShareInvite(+ $0.WebShareInviteRef request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$closeWebShareInvite, request, options: options);+ }++ /// 移除一台登记过的手机,它的网页立即失效+ $grpc.ResponseFuture<$0.WebShareStatus> removeWebSession(+ $0.WebSessionRef request, {+ $grpc.CallOptions? options,+ }) {+ return $createUnaryCall(_$removeWebSession, request, options: options);+ }+/// 发送窗口、头像里的「粘贴」:剪贴板里是文件时返回它们的路径;是图片时存成 PNG,返回这个文件的路径$grpc.ResponseFuture<$0.PasteFilesResponse> pasteFiles($0.Empty request, {@@ -753,6 +801,35 @@ class DaemonServiceClient extends $grpc.Client {'/pasteferry.v1.DaemonService/BlockDevice',($0.FriendRef value) => value.writeToBuffer(),$0.Empty.fromBuffer);+ static final _$submitText =+ $grpc.ClientMethod<$0.SubmitTextRequest, $0.ClipRecord>(+ '/pasteferry.v1.DaemonService/SubmitText',+ ($0.SubmitTextRequest value) => value.writeToBuffer(),+ $0.ClipRecord.fromBuffer);+ static final _$getWebShare = $grpc.ClientMethod<$0.Empty, $0.WebShareStatus>(+ '/pasteferry.v1.DaemonService/GetWebShare',+ ($0.Empty value) => value.writeToBuffer(),+ $0.WebShareStatus.fromBuffer);+ static final _$setWebShare =+ $grpc.ClientMethod<$0.SetWebShareRequest, $0.WebShareStatus>(+ '/pasteferry.v1.DaemonService/SetWebShare',+ ($0.SetWebShareRequest value) => value.writeToBuffer(),+ $0.WebShareStatus.fromBuffer);+ static final _$newWebShareInvite =+ $grpc.ClientMethod<$0.NewWebShareInviteRequest, $0.WebShareInvite>(+ '/pasteferry.v1.DaemonService/NewWebShareInvite',+ ($0.NewWebShareInviteRequest value) => value.writeToBuffer(),+ $0.WebShareInvite.fromBuffer);+ static final _$closeWebShareInvite =+ $grpc.ClientMethod<$0.WebShareInviteRef, $0.Empty>(+ '/pasteferry.v1.DaemonService/CloseWebShareInvite',+ ($0.WebShareInviteRef value) => value.writeToBuffer(),+ $0.Empty.fromBuffer);+ static final _$removeWebSession =+ $grpc.ClientMethod<$0.WebSessionRef, $0.WebShareStatus>(+ '/pasteferry.v1.DaemonService/RemoveWebSession',+ ($0.WebSessionRef value) => value.writeToBuffer(),+ $0.WebShareStatus.fromBuffer);static final _$pasteFiles =$grpc.ClientMethod<$0.Empty, $0.PasteFilesResponse>('/pasteferry.v1.DaemonService/PasteFiles',@@ -1185,6 +1262,51 @@ abstract class DaemonServiceBase extends $grpc.Service {false,($core.List<$core.int> value) => $0.FriendRef.fromBuffer(value),($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.SubmitTextRequest, $0.ClipRecord>(+ 'SubmitText',+ submitText_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.SubmitTextRequest.fromBuffer(value),+ ($0.ClipRecord value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.Empty, $0.WebShareStatus>(+ 'GetWebShare',+ getWebShare_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.Empty.fromBuffer(value),+ ($0.WebShareStatus value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.SetWebShareRequest, $0.WebShareStatus>(+ 'SetWebShare',+ setWebShare_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.SetWebShareRequest.fromBuffer(value),+ ($0.WebShareStatus value) => value.writeToBuffer()));+ $addMethod(+ $grpc.ServiceMethod<$0.NewWebShareInviteRequest, $0.WebShareInvite>(+ 'NewWebShareInvite',+ newWebShareInvite_Pre,+ false,+ false,+ ($core.List<$core.int> value) =>+ $0.NewWebShareInviteRequest.fromBuffer(value),+ ($0.WebShareInvite value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.WebShareInviteRef, $0.Empty>(+ 'CloseWebShareInvite',+ closeWebShareInvite_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.WebShareInviteRef.fromBuffer(value),+ ($0.Empty value) => value.writeToBuffer()));+ $addMethod($grpc.ServiceMethod<$0.WebSessionRef, $0.WebShareStatus>(+ 'RemoveWebSession',+ removeWebSession_Pre,+ false,+ false,+ ($core.List<$core.int> value) => $0.WebSessionRef.fromBuffer(value),+ ($0.WebShareStatus value) => value.writeToBuffer()));$addMethod($grpc.ServiceMethod<$0.Empty, $0.PasteFilesResponse>('PasteFiles',pasteFiles_Pre,@@ -1639,6 +1761,55 @@ abstract class DaemonServiceBase extends $grpc.Service {$async.Future<$0.Empty> blockDevice($grpc.ServiceCall call, $0.FriendRef request);+ $async.Future<$0.ClipRecord> submitText_Pre($grpc.ServiceCall $call,+ $async.Future<$0.SubmitTextRequest> $request) async {+ return submitText($call, await $request);+ }++ $async.Future<$0.ClipRecord> submitText(+ $grpc.ServiceCall call, $0.SubmitTextRequest request);++ $async.Future<$0.WebShareStatus> getWebShare_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {+ return getWebShare($call, await $request);+ }++ $async.Future<$0.WebShareStatus> getWebShare(+ $grpc.ServiceCall call, $0.Empty request);++ $async.Future<$0.WebShareStatus> setWebShare_Pre($grpc.ServiceCall $call,+ $async.Future<$0.SetWebShareRequest> $request) async {+ return setWebShare($call, await $request);+ }++ $async.Future<$0.WebShareStatus> setWebShare(+ $grpc.ServiceCall call, $0.SetWebShareRequest request);++ $async.Future<$0.WebShareInvite> newWebShareInvite_Pre(+ $grpc.ServiceCall $call,+ $async.Future<$0.NewWebShareInviteRequest> $request) async {+ return newWebShareInvite($call, await $request);+ }++ $async.Future<$0.WebShareInvite> newWebShareInvite(+ $grpc.ServiceCall call, $0.NewWebShareInviteRequest request);++ $async.Future<$0.Empty> closeWebShareInvite_Pre($grpc.ServiceCall $call,+ $async.Future<$0.WebShareInviteRef> $request) async {+ return closeWebShareInvite($call, await $request);+ }++ $async.Future<$0.Empty> closeWebShareInvite(+ $grpc.ServiceCall call, $0.WebShareInviteRef request);++ $async.Future<$0.WebShareStatus> removeWebSession_Pre(+ $grpc.ServiceCall $call, $async.Future<$0.WebSessionRef> $request) async {+ return removeWebSession($call, await $request);+ }++ $async.Future<$0.WebShareStatus> removeWebSession(+ $grpc.ServiceCall call, $0.WebSessionRef request);+$async.Future<$0.PasteFilesResponse> pasteFiles_Pre($grpc.ServiceCall $call, $async.Future<$0.Empty> $request) async {return pasteFiles($call, await $request);diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dartindex 26be5b1..7f171f7 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart@@ -222,6 +222,7 @@ const ClipRecord$json = {},{'1': 'is_link', '3': 17, '4': 1, '5': 8, '10': 'isLink'},{'1': 'alias', '3': 18, '4': 1, '5': 9, '10': 'alias'},+ {'1': 'via_name', '3': 19, '4': 1, '5': 9, '10': 'viaName'},],};@@ -238,7 +239,7 @@ final $typed_data.Uint8List clipRecordDescriptor = $convert.base64Decode('IAEoCVIFZXJyb3ISHwoLaW1hZ2VfY291bnQYDSABKAVSCmltYWdlQ291bnQSGgoIZmF2b3JpdG''UYDiABKAhSCGZhdm9yaXRlEhwKCWZhdm9yaXRlZBgPIAEoCFIJZmF2b3JpdGVkEioKEWZhdm9y''aXRlZF9hdF91bml4GBAgASgDUg9mYXZvcml0ZWRBdFVuaXgSFwoHaXNfbGluaxgRIAEoCFIGaX'- 'NMaW5rEhQKBWFsaWFzGBIgASgJUgVhbGlhcw==');+ 'NMaW5rEhQKBWFsaWFzGBIgASgJUgVhbGlhcxIZCgh2aWFfbmFtZRgTIAEoCVIHdmlhTmFtZQ==');@$core.Deprecated('Use subscribeRequestDescriptor instead')const SubscribeRequest$json = {@@ -453,6 +454,15 @@ const Event$json = {'9': 0,'10': 'profileChanged'},+ {+ '1': 'web_share_changed',+ '3': 18,+ '4': 1,+ '5': 11,+ '6': '.pasteferry.v1.WebShareStatus',+ '9': 0,+ '10': 'webShareChanged'+ },],'8': [{'1': 'payload'},@@ -480,7 +490,8 @@ final $typed_data.Uint8List eventDescriptor = $convert.base64Decode('ZnJpZW5kX3JlbW92ZWQYDyABKAlIAFINZnJpZW5kUmVtb3ZlZBJFCg5mcmllbmRfcmVxdWVzdB''gQIAEoCzIcLnBhc3RlZmVycnkudjEuRnJpZW5kUmVxdWVzdEgAUg1mcmllbmRSZXF1ZXN0EkEK''D3Byb2ZpbGVfY2hhbmdlZBgRIAEoCzIWLnBhc3RlZmVycnkudjEuUHJvZmlsZUgAUg5wcm9maW'- 'xlQ2hhbmdlZEIJCgdwYXlsb2Fk');+ 'xlQ2hhbmdlZBJLChF3ZWJfc2hhcmVfY2hhbmdlZBgSIAEoCzIdLnBhc3RlZmVycnkudjEuV2Vi'+ 'U2hhcmVTdGF0dXNIAFIPd2ViU2hhcmVDaGFuZ2VkQgkKB3BheWxvYWQ=');@$core.Deprecated('Use profileDescriptor instead')const Profile$json = {@@ -934,13 +945,15 @@ const ClipDetail$json = {{'1': 'text', '3': 1, '4': 1, '5': 9, '10': 'text'},{'1': 'text_length', '3': 2, '4': 1, '5': 5, '10': 'textLength'},{'1': 'source_paths', '3': 3, '4': 3, '5': 9, '10': 'sourcePaths'},+ {'1': 'local_paths', '3': 4, '4': 3, '5': 9, '10': 'localPaths'},],};/// Descriptor for `ClipDetail`. Decode as a `google.protobuf.DescriptorProto`.final $typed_data.Uint8List clipDetailDescriptor = $convert.base64Decode('CgpDbGlwRGV0YWlsEhIKBHRleHQYASABKAlSBHRleHQSHwoLdGV4dF9sZW5ndGgYAiABKAVSCn'- 'RleHRMZW5ndGgSIQoMc291cmNlX3BhdGhzGAMgAygJUgtzb3VyY2VQYXRocw==');+ 'RleHRMZW5ndGgSIQoMc291cmNlX3BhdGhzGAMgAygJUgtzb3VyY2VQYXRocxIfCgtsb2NhbF9w'+ 'YXRocxgEIAMoCVIKbG9jYWxQYXRocw==');@$core.Deprecated('Use quickPasteStatusDescriptor instead')const QuickPasteStatus$json = {@@ -1953,3 +1966,130 @@ final $typed_data.Uint8List checkReceiveDirResponseDescriptor = $convert.base64D'ChdDaGVja1JlY2VpdmVEaXJSZXNwb25zZRIOCgJvaxgBIAEoCFICb2sSFAoFZXJyb3IYAiABKA''lSBWVycm9yEh0KCmZyZWVfYnl0ZXMYAyABKANSCWZyZWVCeXRlcxISCgRwYXRoGAQgASgJUgRw''YXRo');++@$core.Deprecated('Use submitTextRequestDescriptor instead')+const SubmitTextRequest$json = {+ '1': 'SubmitTextRequest',+ '2': [+ {'1': 'text', '3': 1, '4': 1, '5': 9, '10': 'text'},+ ],+};++/// Descriptor for `SubmitTextRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List submitTextRequestDescriptor = $convert+ .base64Decode('ChFTdWJtaXRUZXh0UmVxdWVzdBISCgR0ZXh0GAEgASgJUgR0ZXh0');++@$core.Deprecated('Use webShareStatusDescriptor instead')+const WebShareStatus$json = {+ '1': 'WebShareStatus',+ '2': [+ {'1': 'enabled', '3': 1, '4': 1, '5': 8, '10': 'enabled'},+ {'1': 'listening', '3': 2, '4': 1, '5': 8, '10': 'listening'},+ {'1': 'port', '3': 3, '4': 1, '5': 5, '10': 'port'},+ {'1': 'port_fallback', '3': 4, '4': 1, '5': 8, '10': 'portFallback'},+ {'1': 'error', '3': 5, '4': 1, '5': 9, '10': 'error'},+ {'1': 'addresses', '3': 6, '4': 3, '5': 9, '10': 'addresses'},+ {+ '1': 'sessions',+ '3': 7,+ '4': 3,+ '5': 11,+ '6': '.pasteferry.v1.WebSession',+ '10': 'sessions'+ },+ {'1': 'invite_used', '3': 8, '4': 1, '5': 9, '10': 'inviteUsed'},+ ],+};++/// Descriptor for `WebShareStatus`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List webShareStatusDescriptor = $convert.base64Decode(+ 'Cg5XZWJTaGFyZVN0YXR1cxIYCgdlbmFibGVkGAEgASgIUgdlbmFibGVkEhwKCWxpc3RlbmluZx'+ 'gCIAEoCFIJbGlzdGVuaW5nEhIKBHBvcnQYAyABKAVSBHBvcnQSIwoNcG9ydF9mYWxsYmFjaxgE'+ 'IAEoCFIMcG9ydEZhbGxiYWNrEhQKBWVycm9yGAUgASgJUgVlcnJvchIcCglhZGRyZXNzZXMYBi'+ 'ADKAlSCWFkZHJlc3NlcxI1CghzZXNzaW9ucxgHIAMoCzIZLnBhc3RlZmVycnkudjEuV2ViU2Vz'+ 'c2lvblIIc2Vzc2lvbnMSHwoLaW52aXRlX3VzZWQYCCABKAlSCmludml0ZVVzZWQ=');++@$core.Deprecated('Use webSessionDescriptor instead')+const WebSession$json = {+ '1': 'WebSession',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ {'1': 'name', '3': 2, '4': 1, '5': 9, '10': 'name'},+ {'1': 'created_at_unix', '3': 3, '4': 1, '5': 3, '10': 'createdAtUnix'},+ {'1': 'last_seen_unix', '3': 4, '4': 1, '5': 3, '10': 'lastSeenUnix'},+ ],+};++/// Descriptor for `WebSession`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List webSessionDescriptor = $convert.base64Decode(+ 'CgpXZWJTZXNzaW9uEg4KAmlkGAEgASgJUgJpZBISCgRuYW1lGAIgASgJUgRuYW1lEiYKD2NyZW'+ 'F0ZWRfYXRfdW5peBgDIAEoA1INY3JlYXRlZEF0VW5peBIkCg5sYXN0X3NlZW5fdW5peBgEIAEo'+ 'A1IMbGFzdFNlZW5Vbml4');++@$core.Deprecated('Use setWebShareRequestDescriptor instead')+const SetWebShareRequest$json = {+ '1': 'SetWebShareRequest',+ '2': [+ {'1': 'enabled', '3': 1, '4': 1, '5': 8, '10': 'enabled'},+ ],+};++/// Descriptor for `SetWebShareRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List setWebShareRequestDescriptor =+ $convert.base64Decode(+ 'ChJTZXRXZWJTaGFyZVJlcXVlc3QSGAoHZW5hYmxlZBgBIAEoCFIHZW5hYmxlZA==');++@$core.Deprecated('Use newWebShareInviteRequestDescriptor instead')+const NewWebShareInviteRequest$json = {+ '1': 'NewWebShareInviteRequest',+ '2': [+ {'1': 'address', '3': 1, '4': 1, '5': 9, '10': 'address'},+ ],+};++/// Descriptor for `NewWebShareInviteRequest`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List newWebShareInviteRequestDescriptor =+ $convert.base64Decode(+ 'ChhOZXdXZWJTaGFyZUludml0ZVJlcXVlc3QSGAoHYWRkcmVzcxgBIAEoCVIHYWRkcmVzcw==');++@$core.Deprecated('Use webShareInviteDescriptor instead')+const WebShareInvite$json = {+ '1': 'WebShareInvite',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ {'1': 'url', '3': 2, '4': 1, '5': 9, '10': 'url'},+ {'1': 'expires_at_unix', '3': 3, '4': 1, '5': 3, '10': 'expiresAtUnix'},+ {'1': 'qr_size', '3': 4, '4': 1, '5': 5, '10': 'qrSize'},+ {'1': 'qr_modules', '3': 5, '4': 1, '5': 12, '10': 'qrModules'},+ ],+};++/// Descriptor for `WebShareInvite`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List webShareInviteDescriptor = $convert.base64Decode(+ 'Cg5XZWJTaGFyZUludml0ZRIOCgJpZBgBIAEoCVICaWQSEAoDdXJsGAIgASgJUgN1cmwSJgoPZX'+ 'hwaXJlc19hdF91bml4GAMgASgDUg1leHBpcmVzQXRVbml4EhcKB3FyX3NpemUYBCABKAVSBnFy'+ 'U2l6ZRIdCgpxcl9tb2R1bGVzGAUgASgMUglxck1vZHVsZXM=');++@$core.Deprecated('Use webShareInviteRefDescriptor instead')+const WebShareInviteRef$json = {+ '1': 'WebShareInviteRef',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ ],+};++/// Descriptor for `WebShareInviteRef`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List webShareInviteRefDescriptor =+ $convert.base64Decode('ChFXZWJTaGFyZUludml0ZVJlZhIOCgJpZBgBIAEoCVICaWQ=');++@$core.Deprecated('Use webSessionRefDescriptor instead')+const WebSessionRef$json = {+ '1': 'WebSessionRef',+ '2': [+ {'1': 'id', '3': 1, '4': 1, '5': 9, '10': 'id'},+ ],+};++/// Descriptor for `WebSessionRef`. Decode as a `google.protobuf.DescriptorProto`.+final $typed_data.Uint8List webSessionRefDescriptor =+ $convert.base64Decode('Cg1XZWJTZXNzaW9uUmVmEg4KAmlkGAEgASgJUgJpZA==');diff --git a/ui/lib/icons.dart b/ui/lib/icons.dartindex eea2b32..bb78255 100644--- a/ui/lib/icons.dart+++ b/ui/lib/icons.dart@@ -72,4 +72,12 @@ abstract final class AppIcons {static IconData get arrowDown => _pick(CupertinoIcons.arrow_down, FluentIcons.arrow_down_24_regular);static IconData get arrowUp => _pick(CupertinoIcons.arrow_up, FluentIcons.arrow_up_24_regular);static IconData get returnKey => _pick(CupertinoIcons.return_icon, FluentIcons.arrow_enter_left_20_regular);+ // 手机网页传输+ static IconData get phone => _pick(CupertinoIcons.device_phone_portrait, FluentIcons.phone_24_regular);+ static IconData get qrCode => _pick(CupertinoIcons.qrcode, FluentIcons.qr_code_24_regular);+ // Android App+ static IconData get copy => _pick(CupertinoIcons.doc_on_doc, FluentIcons.copy_24_regular);+ static IconData get share => _pick(CupertinoIcons.share, FluentIcons.share_android_24_regular);+ static IconData get download => _pick(CupertinoIcons.arrow_down_to_line, FluentIcons.arrow_download_24_regular);+ static IconData get wifiOff => _pick(CupertinoIcons.wifi_slash, FluentIcons.wifi_off_24_regular);}diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arbindex f8b0512..5042962 100644--- a/ui/lib/l10n/app_en.arb+++ b/ui/lib/l10n/app_en.arb@@ -1588,5 +1588,155 @@"type": "String"}}- }+ },+ "webShareTitle": "Phone web transfer",+ "webShareFootnote": "Scan a QR code with a phone to send text, photos and files to and from this computer in the browser, no app needed. The phone and computer need to be on the same network.",+ "webShareSwitch": "Let phones connect in the browser",+ "webShareOn": "On, {count} phone(s)",+ "@webShareOn": {+ "placeholders": {+ "count": {+ "type": "int"+ }+ }+ },+ "webShareOff": "Off",+ "webShareShowQr": "Show QR code",+ "webShareDialogTitle": "Scan with your phone",+ "webShareDialogBody": "Scan with the phone’s camera or browser and open it in the browser. Each QR code registers one phone and is replaced after use.",+ "webShareAddress": "Address",+ "webShareSecurity": "Content is encrypted in the page, so others on the network can’t read it. But the page itself is http and can’t stop someone who deliberately tampers with it. Use it at home or on a trusted office network, not on public Wi-Fi.",+ "webSharePhones": "Registered phones",+ "webShareNoPhones": "No phones yet",+ "webShareLastUsed": "Last used {time}",+ "@webShareLastUsed": {+ "placeholders": {+ "time": {+ "type": "String"+ }+ }+ },+ "webShareRemove": "Remove",+ "webShareRemoved": "Removed “{name}”",+ "@webShareRemoved": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "webShareNewPhone": "“{name}” registered",+ "@webShareNewPhone": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "webShareNotListening": "Couldn’t start listening: {error}",+ "@webShareNotListening": {+ "placeholders": {+ "error": {+ "type": "String"+ }+ }+ },+ "webSharePortFallback": "The usual port is taken, so a temporary one is in use. Saved addresses won’t open until phones scan again.",+ "webShareNoAddress": "No local network address. Connect to Wi-Fi or a wired network first.",+ "webShareCantOpen": "If the page won’t open on the phone, make sure both are on the same network (guest networks usually don’t work). On Windows, PasteFerry also needs to be allowed through the firewall.",+ "mTabRecords": "History",+ "mTabSend": "Send",+ "mThisPhone": "This phone",+ "mThisPhoneName": "This phone: {name}",+ "@mThisPhoneName": {+ "placeholders": {+ "name": {+ "type": "String"+ }+ }+ },+ "mSendTitle": "Send to your computer",+ "mSendHint": "Type or paste text",+ "mPaste": "Paste",+ "mClipboardNoText": "The clipboard has no text",+ "mSendAction": "Send",+ "mSendTo": "Goes to {names}",+ "@mSendTo": {+ "placeholders": {+ "names": {+ "type": "String"+ }+ }+ },+ "mNoOnlineDevices": "No devices online nearby",+ "mNoPairedDevices": "Pair with a computer first",+ "mSent": "Sent",+ "mSendFootnote": "The text goes into the computer’s history and onto its clipboard, as if you had copied it there. Text you copy on this phone isn’t sent automatically: paste it here and tap Send.",+ "mSendFailed": "Couldn’t send: {detail}",+ "@mSendFailed": {+ "placeholders": {+ "detail": {+ "type": "String"+ }+ }+ },+ "mCopy": "Copy",+ "mCopied": "Copied to this phone’s clipboard",+ "mShare": "Share",+ "mSaved": "Saved to Photos or Download/PasteFerry",+ "mActionFailed": "Didn’t work: {detail}",+ "@mActionFailed": {+ "placeholders": {+ "detail": {+ "type": "String"+ }+ }+ },+ "mDownloading": "Downloading…",+ "mNotDownloaded": "Not downloaded yet",+ "mDownloadHint": "It downloads first when you tap Copy, Save or Share.",+ "mFullTextLoading": "Loading…",+ "mTextTruncated": "Showing the first {shown} of {total} characters. Copy gets all of it.",+ "@mTextTruncated": {+ "placeholders": {+ "shown": {+ "type": "int"+ },+ "total": {+ "type": "int"+ }+ }+ },+ "mNotOnLanTitle": "Not on Wi-Fi",+ "mNotOnLanBody": "For now PasteFerry syncs only on the local network. Join the same Wi-Fi as your computer.",+ "mStartFailed": "PasteFerry couldn’t start: {detail}",+ "@mStartFailed": {+ "placeholders": {+ "detail": {+ "type": "String"+ }+ }+ },+ "mNoDevicesBody": "On your computer, open PasteFerry → Devices → Add device, then enter the code it shows here. On the same Wi-Fi you can also open “Search nearby” on both.",+ "mSectionSync": "Sync",+ "mSectionBackground": "Background",+ "mAutoApplyDesc": "Text copied on your computer goes straight onto this phone’s clipboard. Images and files wait until you tap Copy.",+ "mKeepAlive": "Stay connected in the background",+ "mKeepAliveDesc": "Receive text even when PasteFerry isn’t open. Shows an ongoing notification.",+ "mNotifications": "Notifications",+ "mNotificationsDesc": "Needed for the ongoing notification. PasteFerry works without it.",+ "mBattery": "Run in the background",+ "mBatteryDesc": "Turn off battery optimization so the system doesn’t stop PasteFerry when the screen is locked. Some phones also need PasteFerry added to their auto-start or background list in Settings.",+ "mAllowed": "Allowed",+ "mAllow": "Allow",+ "mVersion": "Version {version}",+ "@mVersion": {+ "placeholders": {+ "version": {+ "type": "String"+ }+ }+ },+ "mDeleteConfirm": "Delete this record?",+ "mDelete": "Delete"}diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arbindex 4cbb882..ba8e2a4 100644--- a/ui/lib/l10n/app_ja.arb+++ b/ui/lib/l10n/app_ja.arb@@ -618,5 +618,68 @@"friendsSearch": "連絡先を検索","friendsNoMatch": "一致する連絡先はありません","friendsPick": "連絡先を選ぶと、転送履歴の確認やファイル送信ができます",- "friendDropHint": "ここにドロップすると {name} に送ります"+ "friendDropHint": "ここにドロップすると {name} に送ります",+ "webShareTitle": "スマートフォンの Web 転送",+ "webShareFootnote": "スマートフォンで QR コードを読み取ると、アプリなしでブラウザからこのコンピュータとテキスト、写真、ファイルをやり取りできます。同じネットワークにつながっている必要があります。",+ "webShareSwitch": "ブラウザからの接続を許可",+ "webShareOn": "オン、スマートフォン {count} 台",+ "webShareOff": "オフ",+ "webShareShowQr": "QR コードを表示",+ "webShareDialogTitle": "スマートフォンで読み取る",+ "webShareDialogBody": "スマートフォンのカメラやブラウザで読み取り、ブラウザで開きます。1 つの QR コードで登録できるのは 1 台で、使うと新しいものに替わります。",+ "webShareAddress": "アドレス",+ "webShareSecurity": "内容はページ内で暗号化され、同じネットワークの他の人には読めません。ただしページ自体は http のため、意図的な改ざんは防げません。自宅や信頼できる職場のネットワークで使い、公衆 Wi-Fi では使わないでください。",+ "webSharePhones": "登録済みのスマートフォン",+ "webShareNoPhones": "まだありません",+ "webShareLastUsed": "最終使用 {time}",+ "webShareRemove": "削除",+ "webShareRemoved": "「{name}」を削除しました",+ "webShareNewPhone": "「{name}」を登録しました",+ "webShareNotListening": "待ち受けを開始できませんでした:{error}",+ "webSharePortFallback": "通常のポートが使用中のため、一時的なポートを使っています。保存したアドレスは開けないため、読み取り直してください。",+ "webShareNoAddress": "ローカルネットワークのアドレスがありません。先に Wi-Fi か有線ネットワークにつないでください。",+ "webShareCantOpen": "スマートフォンでページが開けないときは、同じネットワークにいるか確認してください(ゲストネットワークでは通常つながりません)。Windows ではファイアウォールで PasteFerry を許可する必要もあります。",+ "mTabRecords": "履歴",+ "mTabSend": "送信",+ "mThisPhone": "このスマホ",+ "mThisPhoneName": "このスマホ:{name}",+ "mSendTitle": "パソコンへ送る",+ "mSendHint": "テキストを入力または貼り付け",+ "mPaste": "貼り付け",+ "mClipboardNoText": "クリップボードにテキストがありません",+ "mSendAction": "送信",+ "mSendTo": "{names} に送信します",+ "mNoOnlineDevices": "近くにオンラインのデバイスがありません",+ "mNoPairedDevices": "先にパソコンとペアリングしてください",+ "mSent": "送信しました",+ "mSendFootnote": "テキストはパソコンの履歴に入り、パソコンの設定どおりクリップボードにも入ります。パソコンでコピーしたのと同じです。スマホでコピーした内容は自動では送られないので、ここに貼り付けて送信してください。",+ "mSendFailed": "送信できませんでした:{detail}",+ "mCopy": "コピー",+ "mCopied": "スマホのクリップボードにコピーしました",+ "mShare": "共有",+ "mSaved": "写真または「Download/PasteFerry」に保存しました",+ "mActionFailed": "できませんでした:{detail}",+ "mDownloading": "ダウンロード中…",+ "mNotDownloaded": "未ダウンロード",+ "mDownloadHint": "「コピー」「保存」「共有」をタップすると先にダウンロードします。",+ "mFullTextLoading": "読み込み中…",+ "mTextTruncated": "全 {total} 文字のうち最初の {shown} 文字を表示しています。コピーされるのは全文です。",+ "mNotOnLanTitle": "Wi-Fi に接続していません",+ "mNotOnLanBody": "現在はローカルネットワーク内でのみ同期します。パソコンと同じ Wi-Fi に接続してください。",+ "mStartFailed": "PasteFerry を起動できませんでした:{detail}",+ "mNoDevicesBody": "パソコンで PasteFerry の「デバイス → デバイスを追加」を開き、表示されたコードをここに入力します。同じ Wi-Fi なら、両方で「近くのデバイスを探す」を開いても構いません。",+ "mSectionSync": "同期",+ "mSectionBackground": "バックグラウンド",+ "mAutoApplyDesc": "パソコンでコピーしたテキストをそのままスマホのクリップボードに入れます。画像とファイルは「コピー」をタップしたときだけです。",+ "mKeepAlive": "バックグラウンドで接続を保つ",+ "mKeepAliveDesc": "PasteFerry を開いていなくてもテキストを受け取れます。常駐通知が表示されます。",+ "mNotifications": "通知",+ "mNotificationsDesc": "常駐通知に必要です。許可しなくても使えます。",+ "mBattery": "バックグラウンドでの実行",+ "mBatteryDesc": "電池の最適化をオフにすると、画面ロック中にシステムに停止されにくくなります。機種によっては設定で自動起動やバックグラウンド実行の許可も必要です。",+ "mAllowed": "許可済み",+ "mAllow": "許可",+ "mVersion": "バージョン {version}",+ "mDeleteConfirm": "この履歴を削除しますか?",+ "mDelete": "削除"}diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dartindex 17bdc67..e952b2d 100644--- a/ui/lib/l10n/app_localizations.dart+++ b/ui/lib/l10n/app_localizations.dart@@ -3823,6 +3823,384 @@ abstract class AppLocalizations {/// In en, this message translates to:/// **'Drop files here to send them to {name}'**String friendDropHint(String name);++ /// No description provided for @webShareTitle.+ ///+ /// In en, this message translates to:+ /// **'Phone web transfer'**+ String get webShareTitle;++ /// No description provided for @webShareFootnote.+ ///+ /// In en, this message translates to:+ /// **'Scan a QR code with a phone to send text, photos and files to and from this computer in the browser, no app needed. The phone and computer need to be on the same network.'**+ String get webShareFootnote;++ /// No description provided for @webShareSwitch.+ ///+ /// In en, this message translates to:+ /// **'Let phones connect in the browser'**+ String get webShareSwitch;++ /// No description provided for @webShareOn.+ ///+ /// In en, this message translates to:+ /// **'On, {count} phone(s)'**+ String webShareOn(int count);++ /// No description provided for @webShareOff.+ ///+ /// In en, this message translates to:+ /// **'Off'**+ String get webShareOff;++ /// No description provided for @webShareShowQr.+ ///+ /// In en, this message translates to:+ /// **'Show QR code'**+ String get webShareShowQr;++ /// No description provided for @webShareDialogTitle.+ ///+ /// In en, this message translates to:+ /// **'Scan with your phone'**+ String get webShareDialogTitle;++ /// No description provided for @webShareDialogBody.+ ///+ /// In en, this message translates to:+ /// **'Scan with the phone’s camera or browser and open it in the browser. Each QR code registers one phone and is replaced after use.'**+ String get webShareDialogBody;++ /// No description provided for @webShareAddress.+ ///+ /// In en, this message translates to:+ /// **'Address'**+ String get webShareAddress;++ /// No description provided for @webShareSecurity.+ ///+ /// In en, this message translates to:+ /// **'Content is encrypted in the page, so others on the network can’t read it. But the page itself is http and can’t stop someone who deliberately tampers with it. Use it at home or on a trusted office network, not on public Wi-Fi.'**+ String get webShareSecurity;++ /// No description provided for @webSharePhones.+ ///+ /// In en, this message translates to:+ /// **'Registered phones'**+ String get webSharePhones;++ /// No description provided for @webShareNoPhones.+ ///+ /// In en, this message translates to:+ /// **'No phones yet'**+ String get webShareNoPhones;++ /// No description provided for @webShareLastUsed.+ ///+ /// In en, this message translates to:+ /// **'Last used {time}'**+ String webShareLastUsed(String time);++ /// No description provided for @webShareRemove.+ ///+ /// In en, this message translates to:+ /// **'Remove'**+ String get webShareRemove;++ /// No description provided for @webShareRemoved.+ ///+ /// In en, this message translates to:+ /// **'Removed “{name}”'**+ String webShareRemoved(String name);++ /// No description provided for @webShareNewPhone.+ ///+ /// In en, this message translates to:+ /// **'“{name}” registered'**+ String webShareNewPhone(String name);++ /// No description provided for @webShareNotListening.+ ///+ /// In en, this message translates to:+ /// **'Couldn’t start listening: {error}'**+ String webShareNotListening(String error);++ /// No description provided for @webSharePortFallback.+ ///+ /// In en, this message translates to:+ /// **'The usual port is taken, so a temporary one is in use. Saved addresses won’t open until phones scan again.'**+ String get webSharePortFallback;++ /// No description provided for @webShareNoAddress.+ ///+ /// In en, this message translates to:+ /// **'No local network address. Connect to Wi-Fi or a wired network first.'**+ String get webShareNoAddress;++ /// No description provided for @webShareCantOpen.+ ///+ /// In en, this message translates to:+ /// **'If the page won’t open on the phone, make sure both are on the same network (guest networks usually don’t work). On Windows, PasteFerry also needs to be allowed through the firewall.'**+ String get webShareCantOpen;++ /// No description provided for @mTabRecords.+ ///+ /// In en, this message translates to:+ /// **'History'**+ String get mTabRecords;++ /// No description provided for @mTabSend.+ ///+ /// In en, this message translates to:+ /// **'Send'**+ String get mTabSend;++ /// No description provided for @mThisPhone.+ ///+ /// In en, this message translates to:+ /// **'This phone'**+ String get mThisPhone;++ /// No description provided for @mThisPhoneName.+ ///+ /// In en, this message translates to:+ /// **'This phone: {name}'**+ String mThisPhoneName(String name);++ /// No description provided for @mSendTitle.+ ///+ /// In en, this message translates to:+ /// **'Send to your computer'**+ String get mSendTitle;++ /// No description provided for @mSendHint.+ ///+ /// In en, this message translates to:+ /// **'Type or paste text'**+ String get mSendHint;++ /// No description provided for @mPaste.+ ///+ /// In en, this message translates to:+ /// **'Paste'**+ String get mPaste;++ /// No description provided for @mClipboardNoText.+ ///+ /// In en, this message translates to:+ /// **'The clipboard has no text'**+ String get mClipboardNoText;++ /// No description provided for @mSendAction.+ ///+ /// In en, this message translates to:+ /// **'Send'**+ String get mSendAction;++ /// No description provided for @mSendTo.+ ///+ /// In en, this message translates to:+ /// **'Goes to {names}'**+ String mSendTo(String names);++ /// No description provided for @mNoOnlineDevices.+ ///+ /// In en, this message translates to:+ /// **'No devices online nearby'**+ String get mNoOnlineDevices;++ /// No description provided for @mNoPairedDevices.+ ///+ /// In en, this message translates to:+ /// **'Pair with a computer first'**+ String get mNoPairedDevices;++ /// No description provided for @mSent.+ ///+ /// In en, this message translates to:+ /// **'Sent'**+ String get mSent;++ /// No description provided for @mSendFootnote.+ ///+ /// In en, this message translates to:+ /// **'The text goes into the computer’s history and onto its clipboard, as if you had copied it there. Text you copy on this phone isn’t sent automatically: paste it here and tap Send.'**+ String get mSendFootnote;++ /// No description provided for @mSendFailed.+ ///+ /// In en, this message translates to:+ /// **'Couldn’t send: {detail}'**+ String mSendFailed(String detail);++ /// No description provided for @mCopy.+ ///+ /// In en, this message translates to:+ /// **'Copy'**+ String get mCopy;++ /// No description provided for @mCopied.+ ///+ /// In en, this message translates to:+ /// **'Copied to this phone’s clipboard'**+ String get mCopied;++ /// No description provided for @mShare.+ ///+ /// In en, this message translates to:+ /// **'Share'**+ String get mShare;++ /// No description provided for @mSaved.+ ///+ /// In en, this message translates to:+ /// **'Saved to Photos or Download/PasteFerry'**+ String get mSaved;++ /// No description provided for @mActionFailed.+ ///+ /// In en, this message translates to:+ /// **'Didn’t work: {detail}'**+ String mActionFailed(String detail);++ /// No description provided for @mDownloading.+ ///+ /// In en, this message translates to:+ /// **'Downloading…'**+ String get mDownloading;++ /// No description provided for @mNotDownloaded.+ ///+ /// In en, this message translates to:+ /// **'Not downloaded yet'**+ String get mNotDownloaded;++ /// No description provided for @mDownloadHint.+ ///+ /// In en, this message translates to:+ /// **'It downloads first when you tap Copy, Save or Share.'**+ String get mDownloadHint;++ /// No description provided for @mFullTextLoading.+ ///+ /// In en, this message translates to:+ /// **'Loading…'**+ String get mFullTextLoading;++ /// No description provided for @mTextTruncated.+ ///+ /// In en, this message translates to:+ /// **'Showing the first {shown} of {total} characters. Copy gets all of it.'**+ String mTextTruncated(int shown, int total);++ /// No description provided for @mNotOnLanTitle.+ ///+ /// In en, this message translates to:+ /// **'Not on Wi-Fi'**+ String get mNotOnLanTitle;++ /// No description provided for @mNotOnLanBody.+ ///+ /// In en, this message translates to:+ /// **'For now PasteFerry syncs only on the local network. Join the same Wi-Fi as your computer.'**+ String get mNotOnLanBody;++ /// No description provided for @mStartFailed.+ ///+ /// In en, this message translates to:+ /// **'PasteFerry couldn’t start: {detail}'**+ String mStartFailed(String detail);++ /// No description provided for @mNoDevicesBody.+ ///+ /// In en, this message translates to:+ /// **'On your computer, open PasteFerry → Devices → Add device, then enter the code it shows here. On the same Wi-Fi you can also open “Search nearby” on both.'**+ String get mNoDevicesBody;++ /// No description provided for @mSectionSync.+ ///+ /// In en, this message translates to:+ /// **'Sync'**+ String get mSectionSync;++ /// No description provided for @mSectionBackground.+ ///+ /// In en, this message translates to:+ /// **'Background'**+ String get mSectionBackground;++ /// No description provided for @mAutoApplyDesc.+ ///+ /// In en, this message translates to:+ /// **'Text copied on your computer goes straight onto this phone’s clipboard. Images and files wait until you tap Copy.'**+ String get mAutoApplyDesc;++ /// No description provided for @mKeepAlive.+ ///+ /// In en, this message translates to:+ /// **'Stay connected in the background'**+ String get mKeepAlive;++ /// No description provided for @mKeepAliveDesc.+ ///+ /// In en, this message translates to:+ /// **'Receive text even when PasteFerry isn’t open. Shows an ongoing notification.'**+ String get mKeepAliveDesc;++ /// No description provided for @mNotifications.+ ///+ /// In en, this message translates to:+ /// **'Notifications'**+ String get mNotifications;++ /// No description provided for @mNotificationsDesc.+ ///+ /// In en, this message translates to:+ /// **'Needed for the ongoing notification. PasteFerry works without it.'**+ String get mNotificationsDesc;++ /// No description provided for @mBattery.+ ///+ /// In en, this message translates to:+ /// **'Run in the background'**+ String get mBattery;++ /// No description provided for @mBatteryDesc.+ ///+ /// In en, this message translates to:+ /// **'Turn off battery optimization so the system doesn’t stop PasteFerry when the screen is locked. Some phones also need PasteFerry added to their auto-start or background list in Settings.'**+ String get mBatteryDesc;++ /// No description provided for @mAllowed.+ ///+ /// In en, this message translates to:+ /// **'Allowed'**+ String get mAllowed;++ /// No description provided for @mAllow.+ ///+ /// In en, this message translates to:+ /// **'Allow'**+ String get mAllow;++ /// No description provided for @mVersion.+ ///+ /// In en, this message translates to:+ /// **'Version {version}'**+ String mVersion(String version);++ /// No description provided for @mDeleteConfirm.+ ///+ /// In en, this message translates to:+ /// **'Delete this record?'**+ String get mDeleteConfirm;++ /// No description provided for @mDelete.+ ///+ /// In en, this message translates to:+ /// **'Delete'**+ String get mDelete;}class _AppLocalizationsDelegatediff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dartindex e4a054a..15961ed 100644--- a/ui/lib/l10n/app_localizations_en.dart+++ b/ui/lib/l10n/app_localizations_en.dart@@ -2335,4 +2335,231 @@ class AppLocalizationsEn extends AppLocalizations {String friendDropHint(String name) {return 'Drop files here to send them to $name';}++ @override+ String get webShareTitle => 'Phone web transfer';++ @override+ String get webShareFootnote =>+ 'Scan a QR code with a phone to send text, photos and files to and from this computer in the browser, no app needed. The phone and computer need to be on the same network.';++ @override+ String get webShareSwitch => 'Let phones connect in the browser';++ @override+ String webShareOn(int count) {+ return 'On, $count phone(s)';+ }++ @override+ String get webShareOff => 'Off';++ @override+ String get webShareShowQr => 'Show QR code';++ @override+ String get webShareDialogTitle => 'Scan with your phone';++ @override+ String get webShareDialogBody =>+ 'Scan with the phone’s camera or browser and open it in the browser. Each QR code registers one phone and is replaced after use.';++ @override+ String get webShareAddress => 'Address';++ @override+ String get webShareSecurity =>+ 'Content is encrypted in the page, so others on the network can’t read it. But the page itself is http and can’t stop someone who deliberately tampers with it. Use it at home or on a trusted office network, not on public Wi-Fi.';++ @override+ String get webSharePhones => 'Registered phones';++ @override+ String get webShareNoPhones => 'No phones yet';++ @override+ String webShareLastUsed(String time) {+ return 'Last used $time';+ }++ @override+ String get webShareRemove => 'Remove';++ @override+ String webShareRemoved(String name) {+ return 'Removed “$name”';+ }++ @override+ String webShareNewPhone(String name) {+ return '“$name” registered';+ }++ @override+ String webShareNotListening(String error) {+ return 'Couldn’t start listening: $error';+ }++ @override+ String get webSharePortFallback =>+ 'The usual port is taken, so a temporary one is in use. Saved addresses won’t open until phones scan again.';++ @override+ String get webShareNoAddress =>+ 'No local network address. Connect to Wi-Fi or a wired network first.';++ @override+ String get webShareCantOpen =>+ 'If the page won’t open on the phone, make sure both are on the same network (guest networks usually don’t work). On Windows, PasteFerry also needs to be allowed through the firewall.';++ @override+ String get mTabRecords => 'History';++ @override+ String get mTabSend => 'Send';++ @override+ String get mThisPhone => 'This phone';++ @override+ String mThisPhoneName(String name) {+ return 'This phone: $name';+ }++ @override+ String get mSendTitle => 'Send to your computer';++ @override+ String get mSendHint => 'Type or paste text';++ @override+ String get mPaste => 'Paste';++ @override+ String get mClipboardNoText => 'The clipboard has no text';++ @override+ String get mSendAction => 'Send';++ @override+ String mSendTo(String names) {+ return 'Goes to $names';+ }++ @override+ String get mNoOnlineDevices => 'No devices online nearby';++ @override+ String get mNoPairedDevices => 'Pair with a computer first';++ @override+ String get mSent => 'Sent';++ @override+ String get mSendFootnote =>+ 'The text goes into the computer’s history and onto its clipboard, as if you had copied it there. Text you copy on this phone isn’t sent automatically: paste it here and tap Send.';++ @override+ String mSendFailed(String detail) {+ return 'Couldn’t send: $detail';+ }++ @override+ String get mCopy => 'Copy';++ @override+ String get mCopied => 'Copied to this phone’s clipboard';++ @override+ String get mShare => 'Share';++ @override+ String get mSaved => 'Saved to Photos or Download/PasteFerry';++ @override+ String mActionFailed(String detail) {+ return 'Didn’t work: $detail';+ }++ @override+ String get mDownloading => 'Downloading…';++ @override+ String get mNotDownloaded => 'Not downloaded yet';++ @override+ String get mDownloadHint =>+ 'It downloads first when you tap Copy, Save or Share.';++ @override+ String get mFullTextLoading => 'Loading…';++ @override+ String mTextTruncated(int shown, int total) {+ return 'Showing the first $shown of $total characters. Copy gets all of it.';+ }++ @override+ String get mNotOnLanTitle => 'Not on Wi-Fi';++ @override+ String get mNotOnLanBody =>+ 'For now PasteFerry syncs only on the local network. Join the same Wi-Fi as your computer.';++ @override+ String mStartFailed(String detail) {+ return 'PasteFerry couldn’t start: $detail';+ }++ @override+ String get mNoDevicesBody =>+ 'On your computer, open PasteFerry → Devices → Add device, then enter the code it shows here. On the same Wi-Fi you can also open “Search nearby” on both.';++ @override+ String get mSectionSync => 'Sync';++ @override+ String get mSectionBackground => 'Background';++ @override+ String get mAutoApplyDesc =>+ 'Text copied on your computer goes straight onto this phone’s clipboard. Images and files wait until you tap Copy.';++ @override+ String get mKeepAlive => 'Stay connected in the background';++ @override+ String get mKeepAliveDesc =>+ 'Receive text even when PasteFerry isn’t open. Shows an ongoing notification.';++ @override+ String get mNotifications => 'Notifications';++ @override+ String get mNotificationsDesc =>+ 'Needed for the ongoing notification. PasteFerry works without it.';++ @override+ String get mBattery => 'Run in the background';++ @override+ String get mBatteryDesc =>+ 'Turn off battery optimization so the system doesn’t stop PasteFerry when the screen is locked. Some phones also need PasteFerry added to their auto-start or background list in Settings.';++ @override+ String get mAllowed => 'Allowed';++ @override+ String get mAllow => 'Allow';++ @override+ String mVersion(String version) {+ return 'Version $version';+ }++ @override+ String get mDeleteConfirm => 'Delete this record?';++ @override+ String get mDelete => 'Delete';}diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dartindex 74e69d2..b2a7fc6 100644--- a/ui/lib/l10n/app_localizations_ja.dart+++ b/ui/lib/l10n/app_localizations_ja.dart@@ -2162,4 +2162,227 @@ class AppLocalizationsJa extends AppLocalizations {String friendDropHint(String name) {return 'ここにドロップすると $name に送ります';}++ @override+ String get webShareTitle => 'スマートフォンの Web 転送';++ @override+ String get webShareFootnote =>+ 'スマートフォンで QR コードを読み取ると、アプリなしでブラウザからこのコンピュータとテキスト、写真、ファイルをやり取りできます。同じネットワークにつながっている必要があります。';++ @override+ String get webShareSwitch => 'ブラウザからの接続を許可';++ @override+ String webShareOn(int count) {+ return 'オン、スマートフォン $count 台';+ }++ @override+ String get webShareOff => 'オフ';++ @override+ String get webShareShowQr => 'QR コードを表示';++ @override+ String get webShareDialogTitle => 'スマートフォンで読み取る';++ @override+ String get webShareDialogBody =>+ 'スマートフォンのカメラやブラウザで読み取り、ブラウザで開きます。1 つの QR コードで登録できるのは 1 台で、使うと新しいものに替わります。';++ @override+ String get webShareAddress => 'アドレス';++ @override+ String get webShareSecurity =>+ '内容はページ内で暗号化され、同じネットワークの他の人には読めません。ただしページ自体は http のため、意図的な改ざんは防げません。自宅や信頼できる職場のネットワークで使い、公衆 Wi-Fi では使わないでください。';++ @override+ String get webSharePhones => '登録済みのスマートフォン';++ @override+ String get webShareNoPhones => 'まだありません';++ @override+ String webShareLastUsed(String time) {+ return '最終使用 $time';+ }++ @override+ String get webShareRemove => '削除';++ @override+ String webShareRemoved(String name) {+ return '「$name」を削除しました';+ }++ @override+ String webShareNewPhone(String name) {+ return '「$name」を登録しました';+ }++ @override+ String webShareNotListening(String error) {+ return '待ち受けを開始できませんでした:$error';+ }++ @override+ String get webSharePortFallback =>+ '通常のポートが使用中のため、一時的なポートを使っています。保存したアドレスは開けないため、読み取り直してください。';++ @override+ String get webShareNoAddress =>+ 'ローカルネットワークのアドレスがありません。先に Wi-Fi か有線ネットワークにつないでください。';++ @override+ String get webShareCantOpen =>+ 'スマートフォンでページが開けないときは、同じネットワークにいるか確認してください(ゲストネットワークでは通常つながりません)。Windows ではファイアウォールで PasteFerry を許可する必要もあります。';++ @override+ String get mTabRecords => '履歴';++ @override+ String get mTabSend => '送信';++ @override+ String get mThisPhone => 'このスマホ';++ @override+ String mThisPhoneName(String name) {+ return 'このスマホ:$name';+ }++ @override+ String get mSendTitle => 'パソコンへ送る';++ @override+ String get mSendHint => 'テキストを入力または貼り付け';++ @override+ String get mPaste => '貼り付け';++ @override+ String get mClipboardNoText => 'クリップボードにテキストがありません';++ @override+ String get mSendAction => '送信';++ @override+ String mSendTo(String names) {+ return '$names に送信します';+ }++ @override+ String get mNoOnlineDevices => '近くにオンラインのデバイスがありません';++ @override+ String get mNoPairedDevices => '先にパソコンとペアリングしてください';++ @override+ String get mSent => '送信しました';++ @override+ String get mSendFootnote =>+ 'テキストはパソコンの履歴に入り、パソコンの設定どおりクリップボードにも入ります。パソコンでコピーしたのと同じです。スマホでコピーした内容は自動では送られないので、ここに貼り付けて送信してください。';++ @override+ String mSendFailed(String detail) {+ return '送信できませんでした:$detail';+ }++ @override+ String get mCopy => 'コピー';++ @override+ String get mCopied => 'スマホのクリップボードにコピーしました';++ @override+ String get mShare => '共有';++ @override+ String get mSaved => '写真または「Download/PasteFerry」に保存しました';++ @override+ String mActionFailed(String detail) {+ return 'できませんでした:$detail';+ }++ @override+ String get mDownloading => 'ダウンロード中…';++ @override+ String get mNotDownloaded => '未ダウンロード';++ @override+ String get mDownloadHint => '「コピー」「保存」「共有」をタップすると先にダウンロードします。';++ @override+ String get mFullTextLoading => '読み込み中…';++ @override+ String mTextTruncated(int shown, int total) {+ return '全 $total 文字のうち最初の $shown 文字を表示しています。コピーされるのは全文です。';+ }++ @override+ String get mNotOnLanTitle => 'Wi-Fi に接続していません';++ @override+ String get mNotOnLanBody => '現在はローカルネットワーク内でのみ同期します。パソコンと同じ Wi-Fi に接続してください。';++ @override+ String mStartFailed(String detail) {+ return 'PasteFerry を起動できませんでした:$detail';+ }++ @override+ String get mNoDevicesBody =>+ 'パソコンで PasteFerry の「デバイス → デバイスを追加」を開き、表示されたコードをここに入力します。同じ Wi-Fi なら、両方で「近くのデバイスを探す」を開いても構いません。';++ @override+ String get mSectionSync => '同期';++ @override+ String get mSectionBackground => 'バックグラウンド';++ @override+ String get mAutoApplyDesc =>+ 'パソコンでコピーしたテキストをそのままスマホのクリップボードに入れます。画像とファイルは「コピー」をタップしたときだけです。';++ @override+ String get mKeepAlive => 'バックグラウンドで接続を保つ';++ @override+ String get mKeepAliveDesc => 'PasteFerry を開いていなくてもテキストを受け取れます。常駐通知が表示されます。';++ @override+ String get mNotifications => '通知';++ @override+ String get mNotificationsDesc => '常駐通知に必要です。許可しなくても使えます。';++ @override+ String get mBattery => 'バックグラウンドでの実行';++ @override+ String get mBatteryDesc =>+ '電池の最適化をオフにすると、画面ロック中にシステムに停止されにくくなります。機種によっては設定で自動起動やバックグラウンド実行の許可も必要です。';++ @override+ String get mAllowed => '許可済み';++ @override+ String get mAllow => '許可';++ @override+ String mVersion(String version) {+ return 'バージョン $version';+ }++ @override+ String get mDeleteConfirm => 'この履歴を削除しますか?';++ @override+ String get mDelete => '削除';}diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dartindex cb0e24a..2208e7d 100644--- a/ui/lib/l10n/app_localizations_zh.dart+++ b/ui/lib/l10n/app_localizations_zh.dart@@ -2138,6 +2138,226 @@ class AppLocalizationsZh extends AppLocalizations {String friendDropHint(String name) {return '松开即可发给 $name';}++ @override+ String get webShareTitle => '手机网页传输';++ @override+ String get webShareFootnote =>+ '手机扫码后用浏览器和这台电脑互传文字、照片和文件,不用装 App。手机和电脑要在同一个网络里。';++ @override+ String get webShareSwitch => '允许手机用网页连接';++ @override+ String webShareOn(int count) {+ return '已打开,$count 台手机';+ }++ @override+ String get webShareOff => '关闭';++ @override+ String get webShareShowQr => '显示二维码';++ @override+ String get webShareDialogTitle => '用手机扫码';++ @override+ String get webShareDialogBody =>+ '用手机的相机或浏览器扫码,在浏览器里打开。一个二维码只能登记一台手机,用过会自动换新。';++ @override+ String get webShareAddress => '地址';++ @override+ String get webShareSecurity =>+ '内容在网页里加密传输,同一网络里的其他人看不到内容;但网页本身是 http,防不住有人存心篡改。请在家里或可信的办公网络里用,公共 Wi-Fi 下不要打开。';++ @override+ String get webSharePhones => '已登记的手机';++ @override+ String get webShareNoPhones => '还没有手机登记';++ @override+ String webShareLastUsed(String time) {+ return '最后使用 $time';+ }++ @override+ String get webShareRemove => '移除';++ @override+ String webShareRemoved(String name) {+ return '已移除「$name」';+ }++ @override+ String webShareNewPhone(String name) {+ return '「$name」已登记';+ }++ @override+ String webShareNotListening(String error) {+ return '没能开始监听:$error';+ }++ @override+ String get webSharePortFallback => '固定端口被占用,用了临时端口:以前收藏的网址打不开,要重新扫码。';++ @override+ String get webShareNoAddress => '没有可用的局域网地址:请先连上 Wi-Fi 或有线网络。';++ @override+ String get webShareCantOpen =>+ '手机打不开网页时,确认两边在同一个网络里,访客网络通常不行;Windows 上还要允许隔空贴通过防火墙。';++ @override+ String get mTabRecords => '记录';++ @override+ String get mTabSend => '发送';++ @override+ String get mThisPhone => '这台手机';++ @override+ String mThisPhoneName(String name) {+ return '这台手机:$name';+ }++ @override+ String get mSendTitle => '发给电脑';++ @override+ String get mSendHint => '输入或粘贴文字';++ @override+ String get mPaste => '粘贴';++ @override+ String get mClipboardNoText => '剪贴板里没有文字';++ @override+ String get mSendAction => '发送';++ @override+ String mSendTo(String names) {+ return '将发给 $names';+ }++ @override+ String get mNoOnlineDevices => '附近没有在线的设备';++ @override+ String get mNoPairedDevices => '先和电脑配对';++ @override+ String get mSent => '已发送';++ @override+ String get mSendFootnote =>+ '文字会进入电脑的复制记录,并按电脑的设置写入剪贴板,就像在电脑上复制了一样。手机上复制的内容不会自动发出,要粘贴到这里再发送。';++ @override+ String mSendFailed(String detail) {+ return '发送失败:$detail';+ }++ @override+ String get mCopy => '复制';++ @override+ String get mCopied => '已复制到手机剪贴板';++ @override+ String get mShare => '分享';++ @override+ String get mSaved => '已保存到相册或「下载/PasteFerry」';++ @override+ String mActionFailed(String detail) {+ return '没有成功:$detail';+ }++ @override+ String get mDownloading => '正在下载…';++ @override+ String get mNotDownloaded => '还没下载';++ @override+ String get mDownloadHint => '点「复制」「保存」「分享」时会先下载。';++ @override+ String get mFullTextLoading => '正在加载…';++ @override+ String mTextTruncated(int shown, int total) {+ return '只显示前 $shown 个字,共 $total 个。复制的是全文。';+ }++ @override+ String get mNotOnLanTitle => '没有连接 Wi-Fi';++ @override+ String get mNotOnLanBody => '目前只在局域网里同步,请连上和电脑同一个 Wi-Fi。';++ @override+ String mStartFailed(String detail) {+ return '隔空贴没能启动:$detail';+ }++ @override+ String get mNoDevicesBody =>+ '在电脑上打开隔空贴「设备 → 添加设备」,在这里输入它显示的配对码。在同一个 Wi-Fi 里时,也可以两边都打开「搜索附近设备」。';++ @override+ String get mSectionSync => '同步';++ @override+ String get mSectionBackground => '后台';++ @override+ String get mAutoApplyDesc => '电脑上复制的文字直接写入手机剪贴板。图片和文件要点「复制」。';++ @override+ String get mKeepAlive => '后台保持连接';++ @override+ String get mKeepAliveDesc => '不打开隔空贴也能收到文字,会有一条常驻通知。';++ @override+ String get mNotifications => '通知';++ @override+ String get mNotificationsDesc => '常驻通知要用。不允许也能用。';++ @override+ String get mBattery => '允许后台运行';++ @override+ String get mBatteryDesc =>+ '关闭电池优化,锁屏后不容易被系统停掉。有的手机还要在系统设置里把隔空贴加入「自启动」或「后台运行」名单。';++ @override+ String get mAllowed => '已允许';++ @override+ String get mAllow => '允许';++ @override+ String mVersion(String version) {+ return '版本 $version';+ }++ @override+ String get mDeleteConfirm => '删除这条记录?';++ @override+ String get mDelete => '删除';}/// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`).@@ -4274,6 +4494,226 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {String friendDropHint(String name) {return '放開即可傳給 $name';}++ @override+ String get webShareTitle => '手機網頁傳輸';++ @override+ String get webShareFootnote =>+ '手機掃碼後用瀏覽器和這部電腦互傳文字、相片和檔案,不用安裝 App。手機和電腦要在同一個網絡裡。';++ @override+ String get webShareSwitch => '允許手機用網頁連接';++ @override+ String webShareOn(int count) {+ return '已開啟,$count 部手機';+ }++ @override+ String get webShareOff => '關閉';++ @override+ String get webShareShowQr => '顯示二維碼';++ @override+ String get webShareDialogTitle => '用手機掃碼';++ @override+ String get webShareDialogBody =>+ '用手機的相機或瀏覽器掃碼,在瀏覽器裡開啟。一個二維碼只能登記一部手機,用過會自動換新。';++ @override+ String get webShareAddress => '地址';++ @override+ String get webShareSecurity =>+ '內容在網頁裡加密傳輸,同一網絡裡的其他人看不到內容;但網頁本身是 http,防不住有人存心竄改。請在家裡或可信任的辦公網絡裡用,公共 Wi-Fi 下不要開啟。';++ @override+ String get webSharePhones => '已登記的手機';++ @override+ String get webShareNoPhones => '還沒有手機登記';++ @override+ String webShareLastUsed(String time) {+ return '最後使用 $time';+ }++ @override+ String get webShareRemove => '移除';++ @override+ String webShareRemoved(String name) {+ return '已移除「$name」';+ }++ @override+ String webShareNewPhone(String name) {+ return '「$name」已登記';+ }++ @override+ String webShareNotListening(String error) {+ return '沒能開始監聽:$error';+ }++ @override+ String get webSharePortFallback => '固定端口被佔用,用了臨時端口:以前收藏的網址打不開,要重新掃碼。';++ @override+ String get webShareNoAddress => '沒有可用的區域網絡地址:請先連上 Wi-Fi 或有線網絡。';++ @override+ String get webShareCantOpen =>+ '手機打不開網頁時,確認兩邊在同一個網絡裡,訪客網絡通常不行;Windows 上還要允許隔空貼通過防火牆。';++ @override+ String get mTabRecords => '記錄';++ @override+ String get mTabSend => '傳送';++ @override+ String get mThisPhone => '這部手機';++ @override+ String mThisPhoneName(String name) {+ return '這部手機:$name';+ }++ @override+ String get mSendTitle => '傳給電腦';++ @override+ String get mSendHint => '輸入或貼上文字';++ @override+ String get mPaste => '貼上';++ @override+ String get mClipboardNoText => '剪貼簿裡沒有文字';++ @override+ String get mSendAction => '傳送';++ @override+ String mSendTo(String names) {+ return '將傳給 $names';+ }++ @override+ String get mNoOnlineDevices => '附近沒有在線的裝置';++ @override+ String get mNoPairedDevices => '先和電腦配對';++ @override+ String get mSent => '已傳送';++ @override+ String get mSendFootnote =>+ '文字會進入電腦的複製記錄,並按電腦的設定寫入剪貼簿,就像在電腦上複製了一樣。手機上複製的內容不會自動送出,要貼到這裡再傳送。';++ @override+ String mSendFailed(String detail) {+ return '傳送失敗:$detail';+ }++ @override+ String get mCopy => '複製';++ @override+ String get mCopied => '已複製到手機剪貼簿';++ @override+ String get mShare => '分享';++ @override+ String get mSaved => '已儲存到相簿或「下載/PasteFerry」';++ @override+ String mActionFailed(String detail) {+ return '沒有成功:$detail';+ }++ @override+ String get mDownloading => '正在下載…';++ @override+ String get mNotDownloaded => '尚未下載';++ @override+ String get mDownloadHint => '點「複製」「儲存」「分享」時會先下載。';++ @override+ String get mFullTextLoading => '正在載入…';++ @override+ String mTextTruncated(int shown, int total) {+ return '只顯示前 $shown 個字,共 $total 個。複製的是全文。';+ }++ @override+ String get mNotOnLanTitle => '沒有連接 Wi-Fi';++ @override+ String get mNotOnLanBody => '目前只在區域網絡裡同步,請連上和電腦同一個 Wi-Fi。';++ @override+ String mStartFailed(String detail) {+ return '隔空貼沒能啟動:$detail';+ }++ @override+ String get mNoDevicesBody =>+ '在電腦上開啟隔空貼「裝置 → 新增裝置」,在這裡輸入它顯示的配對碼。在同一個 Wi-Fi 裡時,也可以兩邊都開啟「搜尋附近裝置」。';++ @override+ String get mSectionSync => '同步';++ @override+ String get mSectionBackground => '背景';++ @override+ String get mAutoApplyDesc => '電腦上複製的文字直接寫入手機剪貼簿。圖片和檔案要點「複製」。';++ @override+ String get mKeepAlive => '背景保持連線';++ @override+ String get mKeepAliveDesc => '不開啟隔空貼也能收到文字,會有一則常駐通知。';++ @override+ String get mNotifications => '通知';++ @override+ String get mNotificationsDesc => '常駐通知要用。不允許也能用。';++ @override+ String get mBattery => '允許背景執行';++ @override+ String get mBatteryDesc =>+ '關閉電池優化,鎖定螢幕後不容易被系統停掉。有的手機還要在系統設定裡把隔空貼加入「自動啟動」或「背景執行」名單。';++ @override+ String get mAllowed => '已允許';++ @override+ String get mAllow => '允許';++ @override+ String mVersion(String version) {+ return '版本 $version';+ }++ @override+ String get mDeleteConfirm => '刪除這條記錄?';++ @override+ String get mDelete => '刪除';}/// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`).@@ -6410,4 +6850,224 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {String friendDropHint(String name) {return '放開即可傳給 $name';}++ @override+ String get webShareTitle => '手機網頁傳輸';++ @override+ String get webShareFootnote =>+ '手機掃碼後用瀏覽器和這台電腦互傳文字、照片和檔案,不用安裝 App。手機和電腦要在同一個網路裡。';++ @override+ String get webShareSwitch => '允許手機用網頁連線';++ @override+ String webShareOn(int count) {+ return '已開啟,$count 支手機';+ }++ @override+ String get webShareOff => '關閉';++ @override+ String get webShareShowQr => '顯示 QR 碼';++ @override+ String get webShareDialogTitle => '用手機掃碼';++ @override+ String get webShareDialogBody =>+ '用手機的相機或瀏覽器掃碼,在瀏覽器裡開啟。一張 QR 碼只能登記一支手機,用過會自動換新。';++ @override+ String get webShareAddress => '位址';++ @override+ String get webShareSecurity =>+ '內容在網頁裡加密傳輸,同一網路裡的其他人看不到內容;但網頁本身是 http,防不住有人存心竄改。請在家裡或可信任的辦公網路裡用,公共 Wi-Fi 下不要開啟。';++ @override+ String get webSharePhones => '已登記的手機';++ @override+ String get webShareNoPhones => '還沒有手機登記';++ @override+ String webShareLastUsed(String time) {+ return '最後使用 $time';+ }++ @override+ String get webShareRemove => '移除';++ @override+ String webShareRemoved(String name) {+ return '已移除「$name」';+ }++ @override+ String webShareNewPhone(String name) {+ return '「$name」已登記';+ }++ @override+ String webShareNotListening(String error) {+ return '沒能開始監聽:$error';+ }++ @override+ String get webSharePortFallback => '固定連接埠被佔用,用了臨時連接埠:以前收藏的網址打不開,要重新掃碼。';++ @override+ String get webShareNoAddress => '沒有可用的區域網路位址:請先連上 Wi-Fi 或有線網路。';++ @override+ String get webShareCantOpen =>+ '手機打不開網頁時,確認兩邊在同一個網路裡,訪客網路通常不行;Windows 上還要允許隔空貼通過防火牆。';++ @override+ String get mTabRecords => '記錄';++ @override+ String get mTabSend => '傳送';++ @override+ String get mThisPhone => '這支手機';++ @override+ String mThisPhoneName(String name) {+ return '這支手機:$name';+ }++ @override+ String get mSendTitle => '傳給電腦';++ @override+ String get mSendHint => '輸入或貼上文字';++ @override+ String get mPaste => '貼上';++ @override+ String get mClipboardNoText => '剪貼簿裡沒有文字';++ @override+ String get mSendAction => '傳送';++ @override+ String mSendTo(String names) {+ return '將傳給 $names';+ }++ @override+ String get mNoOnlineDevices => '附近沒有在線的裝置';++ @override+ String get mNoPairedDevices => '先和電腦配對';++ @override+ String get mSent => '已傳送';++ @override+ String get mSendFootnote =>+ '文字會進入電腦的複製記錄,並依電腦的設定寫入剪貼簿,就像在電腦上複製了一樣。手機上複製的內容不會自動送出,要貼到這裡再傳送。';++ @override+ String mSendFailed(String detail) {+ return '傳送失敗:$detail';+ }++ @override+ String get mCopy => '複製';++ @override+ String get mCopied => '已複製到手機剪貼簿';++ @override+ String get mShare => '分享';++ @override+ String get mSaved => '已儲存到相簿或「下載/PasteFerry」';++ @override+ String mActionFailed(String detail) {+ return '沒有成功:$detail';+ }++ @override+ String get mDownloading => '正在下載…';++ @override+ String get mNotDownloaded => '尚未下載';++ @override+ String get mDownloadHint => '點「複製」「儲存」「分享」時會先下載。';++ @override+ String get mFullTextLoading => '正在載入…';++ @override+ String mTextTruncated(int shown, int total) {+ return '只顯示前 $shown 個字,共 $total 個。複製的是全文。';+ }++ @override+ String get mNotOnLanTitle => '沒有連接 Wi-Fi';++ @override+ String get mNotOnLanBody => '目前只在區域網路裡同步,請連上和電腦同一個 Wi-Fi。';++ @override+ String mStartFailed(String detail) {+ return '隔空貼沒能啟動:$detail';+ }++ @override+ String get mNoDevicesBody =>+ '在電腦上開啟隔空貼「裝置 → 新增裝置」,在這裡輸入它顯示的配對碼。在同一個 Wi-Fi 裡時,也可以兩邊都開啟「搜尋附近裝置」。';++ @override+ String get mSectionSync => '同步';++ @override+ String get mSectionBackground => '背景';++ @override+ String get mAutoApplyDesc => '電腦上複製的文字直接寫入手機剪貼簿。圖片和檔案要點「複製」。';++ @override+ String get mKeepAlive => '背景保持連線';++ @override+ String get mKeepAliveDesc => '不開啟隔空貼也能收到文字,會有一則常駐通知。';++ @override+ String get mNotifications => '通知';++ @override+ String get mNotificationsDesc => '常駐通知要用。不允許也能用。';++ @override+ String get mBattery => '允許背景執行';++ @override+ String get mBatteryDesc =>+ '關閉電池最佳化,鎖定螢幕後不容易被系統停掉。有的手機還要在系統設定裡把隔空貼加入「自動啟動」或「背景執行」名單。';++ @override+ String get mAllowed => '已允許';++ @override+ String get mAllow => '允許';++ @override+ String mVersion(String version) {+ return '版本 $version';+ }++ @override+ String get mDeleteConfirm => '刪除這筆記錄?';++ @override+ String get mDelete => '刪除';}diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arbindex 65a54e2..2b6a42e 100644--- a/ui/lib/l10n/app_zh.arb+++ b/ui/lib/l10n/app_zh.arb@@ -618,5 +618,68 @@"friendsSearch": "搜索好友","friendsNoMatch": "没有找到这个好友","friendsPick": "选一个好友,查看传输记录或发文件",- "friendDropHint": "松开即可发给 {name}"+ "friendDropHint": "松开即可发给 {name}",+ "webShareTitle": "手机网页传输",+ "webShareFootnote": "手机扫码后用浏览器和这台电脑互传文字、照片和文件,不用装 App。手机和电脑要在同一个网络里。",+ "webShareSwitch": "允许手机用网页连接",+ "webShareOn": "已打开,{count} 台手机",+ "webShareOff": "关闭",+ "webShareShowQr": "显示二维码",+ "webShareDialogTitle": "用手机扫码",+ "webShareDialogBody": "用手机的相机或浏览器扫码,在浏览器里打开。一个二维码只能登记一台手机,用过会自动换新。",+ "webShareAddress": "地址",+ "webShareSecurity": "内容在网页里加密传输,同一网络里的其他人看不到内容;但网页本身是 http,防不住有人存心篡改。请在家里或可信的办公网络里用,公共 Wi-Fi 下不要打开。",+ "webSharePhones": "已登记的手机",+ "webShareNoPhones": "还没有手机登记",+ "webShareLastUsed": "最后使用 {time}",+ "webShareRemove": "移除",+ "webShareRemoved": "已移除「{name}」",+ "webShareNewPhone": "「{name}」已登记",+ "webShareNotListening": "没能开始监听:{error}",+ "webSharePortFallback": "固定端口被占用,用了临时端口:以前收藏的网址打不开,要重新扫码。",+ "webShareNoAddress": "没有可用的局域网地址:请先连上 Wi-Fi 或有线网络。",+ "webShareCantOpen": "手机打不开网页时,确认两边在同一个网络里,访客网络通常不行;Windows 上还要允许隔空贴通过防火墙。",+ "mTabRecords": "记录",+ "mTabSend": "发送",+ "mThisPhone": "这台手机",+ "mThisPhoneName": "这台手机:{name}",+ "mSendTitle": "发给电脑",+ "mSendHint": "输入或粘贴文字",+ "mPaste": "粘贴",+ "mClipboardNoText": "剪贴板里没有文字",+ "mSendAction": "发送",+ "mSendTo": "将发给 {names}",+ "mNoOnlineDevices": "附近没有在线的设备",+ "mNoPairedDevices": "先和电脑配对",+ "mSent": "已发送",+ "mSendFootnote": "文字会进入电脑的复制记录,并按电脑的设置写入剪贴板,就像在电脑上复制了一样。手机上复制的内容不会自动发出,要粘贴到这里再发送。",+ "mSendFailed": "发送失败:{detail}",+ "mCopy": "复制",+ "mCopied": "已复制到手机剪贴板",+ "mShare": "分享",+ "mSaved": "已保存到相册或「下载/PasteFerry」",+ "mActionFailed": "没有成功:{detail}",+ "mDownloading": "正在下载…",+ "mNotDownloaded": "还没下载",+ "mDownloadHint": "点「复制」「保存」「分享」时会先下载。",+ "mFullTextLoading": "正在加载…",+ "mTextTruncated": "只显示前 {shown} 个字,共 {total} 个。复制的是全文。",+ "mNotOnLanTitle": "没有连接 Wi-Fi",+ "mNotOnLanBody": "目前只在局域网里同步,请连上和电脑同一个 Wi-Fi。",+ "mStartFailed": "隔空贴没能启动:{detail}",+ "mNoDevicesBody": "在电脑上打开隔空贴「设备 → 添加设备」,在这里输入它显示的配对码。在同一个 Wi-Fi 里时,也可以两边都打开「搜索附近设备」。",+ "mSectionSync": "同步",+ "mSectionBackground": "后台",+ "mAutoApplyDesc": "电脑上复制的文字直接写入手机剪贴板。图片和文件要点「复制」。",+ "mKeepAlive": "后台保持连接",+ "mKeepAliveDesc": "不打开隔空贴也能收到文字,会有一条常驻通知。",+ "mNotifications": "通知",+ "mNotificationsDesc": "常驻通知要用。不允许也能用。",+ "mBattery": "允许后台运行",+ "mBatteryDesc": "关闭电池优化,锁屏后不容易被系统停掉。有的手机还要在系统设置里把隔空贴加入「自启动」或「后台运行」名单。",+ "mAllowed": "已允许",+ "mAllow": "允许",+ "mVersion": "版本 {version}",+ "mDeleteConfirm": "删除这条记录?",+ "mDelete": "删除"}diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arbindex 4e2cf9c..487bf53 100644--- a/ui/lib/l10n/app_zh_Hant_HK.arb+++ b/ui/lib/l10n/app_zh_Hant_HK.arb@@ -618,5 +618,68 @@"friendsSearch": "搜尋好友","friendsNoMatch": "找不到這個好友","friendsPick": "選一個好友,查看傳輸記錄或傳檔案",- "friendDropHint": "放開即可傳給 {name}"+ "friendDropHint": "放開即可傳給 {name}",+ "webShareTitle": "手機網頁傳輸",+ "webShareFootnote": "手機掃碼後用瀏覽器和這部電腦互傳文字、相片和檔案,不用安裝 App。手機和電腦要在同一個網絡裡。",+ "webShareSwitch": "允許手機用網頁連接",+ "webShareOn": "已開啟,{count} 部手機",+ "webShareOff": "關閉",+ "webShareShowQr": "顯示二維碼",+ "webShareDialogTitle": "用手機掃碼",+ "webShareDialogBody": "用手機的相機或瀏覽器掃碼,在瀏覽器裡開啟。一個二維碼只能登記一部手機,用過會自動換新。",+ "webShareAddress": "地址",+ "webShareSecurity": "內容在網頁裡加密傳輸,同一網絡裡的其他人看不到內容;但網頁本身是 http,防不住有人存心竄改。請在家裡或可信任的辦公網絡裡用,公共 Wi-Fi 下不要開啟。",+ "webSharePhones": "已登記的手機",+ "webShareNoPhones": "還沒有手機登記",+ "webShareLastUsed": "最後使用 {time}",+ "webShareRemove": "移除",+ "webShareRemoved": "已移除「{name}」",+ "webShareNewPhone": "「{name}」已登記",+ "webShareNotListening": "沒能開始監聽:{error}",+ "webSharePortFallback": "固定端口被佔用,用了臨時端口:以前收藏的網址打不開,要重新掃碼。",+ "webShareNoAddress": "沒有可用的區域網絡地址:請先連上 Wi-Fi 或有線網絡。",+ "webShareCantOpen": "手機打不開網頁時,確認兩邊在同一個網絡裡,訪客網絡通常不行;Windows 上還要允許隔空貼通過防火牆。",+ "mTabRecords": "記錄",+ "mTabSend": "傳送",+ "mThisPhone": "這部手機",+ "mThisPhoneName": "這部手機:{name}",+ "mSendTitle": "傳給電腦",+ "mSendHint": "輸入或貼上文字",+ "mPaste": "貼上",+ "mClipboardNoText": "剪貼簿裡沒有文字",+ "mSendAction": "傳送",+ "mSendTo": "將傳給 {names}",+ "mNoOnlineDevices": "附近沒有在線的裝置",+ "mNoPairedDevices": "先和電腦配對",+ "mSent": "已傳送",+ "mSendFootnote": "文字會進入電腦的複製記錄,並按電腦的設定寫入剪貼簿,就像在電腦上複製了一樣。手機上複製的內容不會自動送出,要貼到這裡再傳送。",+ "mSendFailed": "傳送失敗:{detail}",+ "mCopy": "複製",+ "mCopied": "已複製到手機剪貼簿",+ "mShare": "分享",+ "mSaved": "已儲存到相簿或「下載/PasteFerry」",+ "mActionFailed": "沒有成功:{detail}",+ "mDownloading": "正在下載…",+ "mNotDownloaded": "尚未下載",+ "mDownloadHint": "點「複製」「儲存」「分享」時會先下載。",+ "mFullTextLoading": "正在載入…",+ "mTextTruncated": "只顯示前 {shown} 個字,共 {total} 個。複製的是全文。",+ "mNotOnLanTitle": "沒有連接 Wi-Fi",+ "mNotOnLanBody": "目前只在區域網絡裡同步,請連上和電腦同一個 Wi-Fi。",+ "mStartFailed": "隔空貼沒能啟動:{detail}",+ "mNoDevicesBody": "在電腦上開啟隔空貼「裝置 → 新增裝置」,在這裡輸入它顯示的配對碼。在同一個 Wi-Fi 裡時,也可以兩邊都開啟「搜尋附近裝置」。",+ "mSectionSync": "同步",+ "mSectionBackground": "背景",+ "mAutoApplyDesc": "電腦上複製的文字直接寫入手機剪貼簿。圖片和檔案要點「複製」。",+ "mKeepAlive": "背景保持連線",+ "mKeepAliveDesc": "不開啟隔空貼也能收到文字,會有一則常駐通知。",+ "mNotifications": "通知",+ "mNotificationsDesc": "常駐通知要用。不允許也能用。",+ "mBattery": "允許背景執行",+ "mBatteryDesc": "關閉電池優化,鎖定螢幕後不容易被系統停掉。有的手機還要在系統設定裡把隔空貼加入「自動啟動」或「背景執行」名單。",+ "mAllowed": "已允許",+ "mAllow": "允許",+ "mVersion": "版本 {version}",+ "mDeleteConfirm": "刪除這條記錄?",+ "mDelete": "刪除"}diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arbindex d1ae557..f5233f5 100644--- a/ui/lib/l10n/app_zh_Hant_TW.arb+++ b/ui/lib/l10n/app_zh_Hant_TW.arb@@ -618,5 +618,68 @@"friendsSearch": "搜尋好友","friendsNoMatch": "沒有找到這個好友","friendsPick": "選一個好友,查看傳輸記錄或傳檔案",- "friendDropHint": "放開即可傳給 {name}"+ "friendDropHint": "放開即可傳給 {name}",+ "webShareTitle": "手機網頁傳輸",+ "webShareFootnote": "手機掃碼後用瀏覽器和這台電腦互傳文字、照片和檔案,不用安裝 App。手機和電腦要在同一個網路裡。",+ "webShareSwitch": "允許手機用網頁連線",+ "webShareOn": "已開啟,{count} 支手機",+ "webShareOff": "關閉",+ "webShareShowQr": "顯示 QR 碼",+ "webShareDialogTitle": "用手機掃碼",+ "webShareDialogBody": "用手機的相機或瀏覽器掃碼,在瀏覽器裡開啟。一張 QR 碼只能登記一支手機,用過會自動換新。",+ "webShareAddress": "位址",+ "webShareSecurity": "內容在網頁裡加密傳輸,同一網路裡的其他人看不到內容;但網頁本身是 http,防不住有人存心竄改。請在家裡或可信任的辦公網路裡用,公共 Wi-Fi 下不要開啟。",+ "webSharePhones": "已登記的手機",+ "webShareNoPhones": "還沒有手機登記",+ "webShareLastUsed": "最後使用 {time}",+ "webShareRemove": "移除",+ "webShareRemoved": "已移除「{name}」",+ "webShareNewPhone": "「{name}」已登記",+ "webShareNotListening": "沒能開始監聽:{error}",+ "webSharePortFallback": "固定連接埠被佔用,用了臨時連接埠:以前收藏的網址打不開,要重新掃碼。",+ "webShareNoAddress": "沒有可用的區域網路位址:請先連上 Wi-Fi 或有線網路。",+ "webShareCantOpen": "手機打不開網頁時,確認兩邊在同一個網路裡,訪客網路通常不行;Windows 上還要允許隔空貼通過防火牆。",+ "mTabRecords": "記錄",+ "mTabSend": "傳送",+ "mThisPhone": "這支手機",+ "mThisPhoneName": "這支手機:{name}",+ "mSendTitle": "傳給電腦",+ "mSendHint": "輸入或貼上文字",+ "mPaste": "貼上",+ "mClipboardNoText": "剪貼簿裡沒有文字",+ "mSendAction": "傳送",+ "mSendTo": "將傳給 {names}",+ "mNoOnlineDevices": "附近沒有在線的裝置",+ "mNoPairedDevices": "先和電腦配對",+ "mSent": "已傳送",+ "mSendFootnote": "文字會進入電腦的複製記錄,並依電腦的設定寫入剪貼簿,就像在電腦上複製了一樣。手機上複製的內容不會自動送出,要貼到這裡再傳送。",+ "mSendFailed": "傳送失敗:{detail}",+ "mCopy": "複製",+ "mCopied": "已複製到手機剪貼簿",+ "mShare": "分享",+ "mSaved": "已儲存到相簿或「下載/PasteFerry」",+ "mActionFailed": "沒有成功:{detail}",+ "mDownloading": "正在下載…",+ "mNotDownloaded": "尚未下載",+ "mDownloadHint": "點「複製」「儲存」「分享」時會先下載。",+ "mFullTextLoading": "正在載入…",+ "mTextTruncated": "只顯示前 {shown} 個字,共 {total} 個。複製的是全文。",+ "mNotOnLanTitle": "沒有連接 Wi-Fi",+ "mNotOnLanBody": "目前只在區域網路裡同步,請連上和電腦同一個 Wi-Fi。",+ "mStartFailed": "隔空貼沒能啟動:{detail}",+ "mNoDevicesBody": "在電腦上開啟隔空貼「裝置 → 新增裝置」,在這裡輸入它顯示的配對碼。在同一個 Wi-Fi 裡時,也可以兩邊都開啟「搜尋附近裝置」。",+ "mSectionSync": "同步",+ "mSectionBackground": "背景",+ "mAutoApplyDesc": "電腦上複製的文字直接寫入手機剪貼簿。圖片和檔案要點「複製」。",+ "mKeepAlive": "背景保持連線",+ "mKeepAliveDesc": "不開啟隔空貼也能收到文字,會有一則常駐通知。",+ "mNotifications": "通知",+ "mNotificationsDesc": "常駐通知要用。不允許也能用。",+ "mBattery": "允許背景執行",+ "mBatteryDesc": "關閉電池最佳化,鎖定螢幕後不容易被系統停掉。有的手機還要在系統設定裡把隔空貼加入「自動啟動」或「背景執行」名單。",+ "mAllowed": "已允許",+ "mAllow": "允許",+ "mVersion": "版本 {version}",+ "mDeleteConfirm": "刪除這筆記錄?",+ "mDelete": "刪除"}diff --git a/ui/lib/main.dart b/ui/lib/main.dartindex b7fc034..f2c68b0 100644--- a/ui/lib/main.dart+++ b/ui/lib/main.dart@@ -8,6 +8,7 @@ import 'gen/pasteferry/v1/daemon.pb.dart' show TransferDirection;import 'background_service.dart';import 'i18n.dart';import 'pages/devices_page.dart';+import 'widgets/web_share.dart';import 'pages/favorites_page.dart';import 'pages/history_page.dart';import 'pages/friends_page.dart';@@ -15,6 +16,7 @@ import 'pages/send_page.dart';import 'pages/service_page.dart';import 'pages/settings_page.dart';import 'pages/official_service_page.dart';+import 'mobile/mobile_app.dart';import 'picker/picker_main.dart';import 'theme.dart';import 'widgets/common.dart';@@ -26,6 +28,11 @@ import 'icons.dart';/// 带 --picker 启动的是快捷粘贴窗口进程,见 picker/picker_main.dart。void main(List<String> args) {+ // Android 是另一套外壳:底部标签、触控尺寸,Go 核心跑在 App 进程里(design/phone-sync.md 3.3.4 节)+ if (Platform.isAndroid) {+ runMobile();+ return;+ }if (args.contains('--picker')) {runPicker();return;@@ -182,6 +189,13 @@ class _ShellState extends State<Shell> with WidgetsBindingObserver {if (state.pageRequest == 'send') _section = Section.send;if (state.pageRequest == 'friends') _section = Section.friends;if (state.pageRequest == 'settings') _section = Section.settings;+ // Windows 托盘的「手机扫码连接」:切到设备页并打开二维码窗口+ if (state.pageRequest == 'webshare' && (state.webShare?.listening ?? false)) {+ _section = Section.devices;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) showWebShareDialog(context);+ });+ }}if (!state.officialEnabled && _section == Section.official) {_section = Section.settings;diff --git a/ui/lib/mobile/devices_tab.dart b/ui/lib/mobile/devices_tab.dartnew file mode 100644index 0000000..5553f7a--- /dev/null+++ b/ui/lib/mobile/devices_tab.dart@@ -0,0 +1,185 @@+import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/pasteferry/v1/daemon.pb.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart' show AppScope;+import '../pages/devices_page.dart' show connectionLabel, platformIcon;+import '../theme.dart';+import '../widgets/common.dart';+import '../widgets/nearby_dialog.dart';+import '../widgets/pairing_dialog.dart';+import 'ui.dart';++/// 设备页:已配对的设备,以及用配对码或「搜索附近设备」配对(design/phone-sync.md 3.2.1 节)。+/// 配对的对话框、指纹核对和桌面共用一套(widgets/pairing_dialog.dart、widgets/nearby_dialog.dart)。+class DevicesTab extends StatelessWidget {+ const DevicesTab({super.key});++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final l = context.l10n;+ final p = context.palette;+ final peers = state.peers;++ final actions = Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.xl),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ FilledButton.icon(+ onPressed: () => showPairingDialog(context),+ icon: Icon(AppIcons.plus, size: 20),+ label: Text(l.addDevice),+ ),+ const SizedBox(height: Insets.sm),+ OutlinedButton.icon(+ onPressed: () => showNearbyDialog(context),+ icon: Icon(AppIcons.radar, size: 20, color: p.text),+ label: Text(l.searchNearby),+ ),+ ],+ ),+ );++ return SafeArea(+ bottom: false,+ child: ListView(+ children: [+ MobileHeader(title: l.navDevices),+ const LanNotice(),+ if (peers.isEmpty) ...[+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, Insets.xl, Insets.xl, Insets.xxl),+ child: EmptyState(+ icon: AppIcons.deviceLaptop,+ title: l.noDevicesTitle,+ description: l.mNoDevicesBody,+ ),+ ),+ actions,+ ] else ...[+ MobileGroup(+ title: l.pairedDevices,+ inset: 56,+ children: [for (final d in peers) _DeviceRow(device: d)],+ ),+ actions,+ ],+ if (state.self != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xl),+ child: Text(+ l.mThisPhoneName(state.self!.name),+ textAlign: TextAlign.center,+ style: context.text.bodySmall,+ ),+ ),+ ],+ ),+ );+ }+}++class _DeviceRow extends StatelessWidget {+ const _DeviceRow({required this.device});++ final Device device;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final l = context.l10n;+ final d = device;+ final synced = !(AppScope.of(context).config?.syncDisabledPeers.contains(d.id) ?? false);+ return MobileTile(+ leading: Icon(platformIcon(d.platform), size: 24, color: p.textDim),+ title: d.name,+ subtitle: [+ d.online ? connectionLabel(d) : l.offline,+ if (!synced) l.syncPaused,+ ].join(' · '),+ trailing: StatusDot(color: d.online ? p.online : p.textFaint, label: ''),+ onTap: () => _showDeviceSheet(context, d),+ );+ }+}++Future<void> _showDeviceSheet(BuildContext context, Device d) => showModalBottomSheet<void>(+ context: context,+ useSafeArea: true,+ builder: (ctx) {+ final state = AppScope.of(ctx);+ final l = ctx.l10n;+ final p = ctx.palette;+ final synced = !(state.config?.syncDisabledPeers.contains(d.id) ?? false);+ return Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.lg),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Icon(platformIcon(d.platform), size: 36, color: p.textDim),+ const SizedBox(height: Insets.sm),+ Text(d.name, style: ctx.text.titleMedium, textAlign: TextAlign.center),+ Text(d.online ? connectionLabel(d) : l.offline, style: ctx.text.bodySmall, textAlign: TextAlign.center),+ const SizedBox(height: Insets.lg),+ Container(+ decoration: BoxDecoration(color: p.fill, borderRadius: BorderRadius.circular(Radii.md)),+ child: MobileTile(+ title: l.peerRealtimeSync,+ trailing: Switch(+ value: synced,+ onChanged: (v) async {+ try {+ await state.setPeerSync(d.id, v);+ } catch (e) {+ if (ctx.mounted) showToast(ctx, AppState.describeError(e), error: true);+ }+ },+ ),+ ),+ ),+ const SizedBox(height: Insets.lg),+ OutlinedButton(+ style: OutlinedButton.styleFrom(foregroundColor: p.danger),+ onPressed: () async {+ Navigator.pop(ctx);+ await _unpair(context, d);+ },+ child: Text(l.unpair),+ ),+ ],+ ),+ );+ },+);++Future<void> _unpair(BuildContext context, Device d) async {+ final state = AppScope.read(context);+ final l = context.l10n;+ final ok = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.unpairTitle(d.name)),+ content: Text(l.unpairBody),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ TextButton(+ style: TextButton.styleFrom(foregroundColor: ctx.palette.danger),+ onPressed: () => Navigator.pop(ctx, true),+ child: Text(l.unpair),+ ),+ ],+ ),+ );+ if (ok != true) return;+ try {+ await state.unpair(d.id);+ if (context.mounted) showToast(context, l.unpaired);+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+}diff --git a/ui/lib/mobile/host.dart b/ui/lib/mobile/host.dartnew file mode 100644index 0000000..47aa58e--- /dev/null+++ b/ui/lib/mobile/host.dart@@ -0,0 +1,40 @@+import 'package:flutter/services.dart';++/// Android 宿主(Kotlin,`android/app/src/main/kotlin/com/pasteferry/app/MainActivity.kt`)提供的几件事。+/// 记录、发送、配对、设置都经 gRPC 直接和 Go 核心说,这里只有 Go 核心做不了的:+/// 启停核心、后台保持连接、保存到相册与「下载」、系统分享、通知与电池优化的权限。+abstract final class Host {+ static const _channel = MethodChannel('pasteferry/host');++ /// 启动 Go 核心(已在运行时什么也不做),返回它的数据目录:daemon.json 就在里面+ static Future<String> start() async {+ final got = await _channel.invokeMapMethod<String, Object?>('start');+ return got!['dataDir']! as String;+ }++ static Future<bool> keepAlive() async => await _channel.invokeMethod<bool>('keepAlive') ?? true;++ static Future<void> setKeepAlive(bool on) => _channel.invokeMethod('setKeepAlive', on);++ /// 图片存进相册,其他文件存进「下载/PasteFerry」。返回存下的文件数+ static Future<int> save(List<String> paths) async =>+ await _channel.invokeMethod<int>('save', {'paths': paths}) ?? 0;++ static Future<void> share(List<String> paths) => _channel.invokeMethod('share', {'paths': paths});++ /// granted、denied(还能请求)或 blocked(只能去系统设置里打开)+ static Future<String> notifications() async =>+ await _channel.invokeMethod<String>('notifications') ?? 'denied';++ static Future<String> requestNotifications() async =>+ await _channel.invokeMethod<String>('requestNotifications') ?? 'denied';++ /// 不受电池优化限制+ static Future<bool> batteryUnrestricted() async =>+ await _channel.invokeMethod<bool>('batteryUnrestricted') ?? false;++ static Future<void> requestBatteryUnrestricted() => _channel.invokeMethod('requestBatteryUnrestricted');++ /// 当前网络是 Wi-Fi 或有线网+ static Future<bool> onLan() async => await _channel.invokeMethod<bool>('onLan') ?? true;+}diff --git a/ui/lib/mobile/mobile_app.dart b/ui/lib/mobile/mobile_app.dartnew file mode 100644index 0000000..bd229c4--- /dev/null+++ b/ui/lib/mobile/mobile_app.dart@@ -0,0 +1,293 @@+import 'package:fluentui_system_icons/fluentui_system_icons.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../app_state.dart';+import '../application_lifecycle.dart' show appNavigatorKey;+import '../daemon_client.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart' show AppScope;+import '../theme.dart';+import '../widgets/common.dart';+import '../widgets/pairing_dialog.dart';+import 'devices_tab.dart';+import 'host.dart';+import 'records_tab.dart';+import 'send_tab.dart';+import 'settings_tab.dart';+import 'ui.dart';++/// Android 的入口:先让宿主拉起 Go 核心、告诉界面数据目录,再像桌面一样经 gRPC 连上去。+void runMobile() {+ WidgetsFlutterBinding.ensureInitialized();+ runApp(const MobileApp());+}++class MobileApp extends StatefulWidget {+ const MobileApp({super.key, this.state});++ /// 测试用:注入预先填好数据的状态,不去启动 Go 核心+ final AppState? state;++ @override+ State<MobileApp> createState() => _MobileAppState();+}++class _MobileAppState extends State<MobileApp> with WidgetsBindingObserver {+ late final AppState _state = widget.state ?? AppState();+ final _themes = <String, (ThemeData, ThemeData)>{};+ String? _startError;++ @override+ void initState() {+ super.initState();+ if (widget.state == null) {+ WidgetsBinding.instance.addObserver(this);+ _start();+ }+ }++ Future<void> _start() async {+ try {+ DaemonEndpoint.androidDataDir = await Host.start();+ if (mounted) setState(() => _startError = null);+ await _state.connect();+ } catch (e) {+ if (mounted) setState(() => _startError = AppState.describeError(e));+ }+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState s) {+ // 关了「后台保持连接」时,离开前台核心就停了;回到前台重新拉起(重复调用无害)+ if (s == AppLifecycleState.resumed) _start();+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ if (widget.state == null) _state.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ return AppScope(+ state: _state,+ child: ListenableBuilder(+ listenable: _state,+ builder: (context, _) {+ final locale = localeFromSetting(_state.config?.language ?? '');+ final language =+ (locale ?? resolveLocale(WidgetsBinding.instance.platformDispatcher.locales)).toLanguageTag();+ final (light, dark) = _themes.putIfAbsent(+ language,+ () => (buildMobileTheme(Brightness.light), buildMobileTheme(Brightness.dark)),+ );+ return MaterialApp(+ title: 'PasteFerry',+ navigatorKey: appNavigatorKey,+ debugShowCheckedModeBanner: false,+ theme: light,+ darkTheme: dark,+ locale: locale,+ supportedLocales: supportedLocales,+ localizationsDelegates: AppLocalizations.localizationsDelegates,+ localeListResolutionCallback: (preferred, _) => resolveLocale(preferred),+ builder: (context, child) {+ appL10n = context.l10n;+ return child!;+ },+ home: MobileShell(startError: _startError, onRetry: _start),+ );+ },+ ),+ );+ }+}++/// 手机上的字号与触控尺寸:配色、圆角沿用桌面的设计系统(theme.dart),+/// 字号放大一档、控件高 48,和网页传输的页面(web/phone)一致。+ThemeData buildMobileTheme(Brightness brightness) {+ final base = buildTheme(brightness);+ final p = base.extension<AppPalette>()!;+ final text = TextTheme(+ headlineMedium: TextStyle(fontSize: 30, fontWeight: FontWeight.w700, color: p.text, letterSpacing: -0.6),+ headlineSmall: TextStyle(fontSize: 22, fontWeight: FontWeight.w600, color: p.text, letterSpacing: -0.4),+ titleLarge: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: p.text, letterSpacing: -0.3),+ titleMedium: TextStyle(fontSize: 17, fontWeight: FontWeight.w600, color: p.text, letterSpacing: -0.2),+ titleSmall: TextStyle(fontSize: 15, fontWeight: FontWeight.w600, color: p.text),+ bodyLarge: TextStyle(fontSize: 16, color: p.text, height: 1.45),+ bodyMedium: TextStyle(fontSize: 15, color: p.text, height: 1.45),+ bodySmall: TextStyle(fontSize: 13, color: p.textDim, height: 1.4),+ labelLarge: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: p.text),+ labelMedium: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: p.textDim),+ labelSmall: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: p.textDim),+ );+ final shape = RoundedRectangleBorder(borderRadius: BorderRadius.circular(Radii.md));+ const padding = EdgeInsets.symmetric(horizontal: 18, vertical: 12);+ return base.copyWith(+ textTheme: text,+ splashFactory: InkRipple.splashFactory,+ highlightColor: p.hover,+ iconTheme: IconThemeData(color: p.textDim, size: 22),+ // 主按钮与次要按钮对应网页的 primary、secondary:强调色底 / 浅灰底,禁用时整体变淡。+ // 桌面共用的对话框里用的 OutlinedButton 也画成浅灰底,和网页一致+ filledButtonTheme: FilledButtonThemeData(+ style: FilledButton.styleFrom(+ backgroundColor: p.accent,+ foregroundColor: Colors.white,+ disabledBackgroundColor: p.accent.withValues(alpha: 0.4),+ disabledForegroundColor: Colors.white.withValues(alpha: 0.8),+ shape: shape,+ padding: padding,+ minimumSize: const Size(0, 48),+ textStyle: text.labelLarge?.copyWith(fontWeight: FontWeight.w600),+ elevation: 0,+ ),+ ),+ outlinedButtonTheme: OutlinedButtonThemeData(+ style: OutlinedButton.styleFrom(+ foregroundColor: p.text,+ backgroundColor: p.fill,+ disabledForegroundColor: p.text.withValues(alpha: 0.4),+ shape: shape,+ padding: padding,+ minimumSize: const Size(0, 48),+ textStyle: text.labelLarge,+ side: BorderSide.none,+ ),+ ),+ textButtonTheme: TextButtonThemeData(+ style: TextButton.styleFrom(+ foregroundColor: p.accent,+ shape: shape,+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),+ minimumSize: const Size(0, 44),+ textStyle: text.labelLarge,+ ),+ ),+ inputDecorationTheme: base.inputDecorationTheme.copyWith(+ isDense: false,+ contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),+ hintStyle: text.bodyLarge?.copyWith(color: p.textFaint),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(Radii.md), borderSide: BorderSide(color: p.border)),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.md),+ borderSide: BorderSide(color: p.border),+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.md),+ borderSide: BorderSide(color: p.accent, width: 1.5),+ ),+ ),+ switchTheme: base.switchTheme.copyWith(materialTapTargetSize: MaterialTapTargetSize.padded),+ dialogTheme: base.dialogTheme.copyWith(titleTextStyle: text.titleMedium, contentTextStyle: text.bodyMedium?.copyWith(color: p.textDim)),+ bottomSheetTheme: BottomSheetThemeData(+ backgroundColor: p.surface,+ surfaceTintColor: Colors.transparent,+ showDragHandle: true,+ dragHandleColor: p.border,+ shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(Radii.lg))),+ ),+ );+}++enum MobileTab { records, send, devices, settings }++class MobileShell extends StatefulWidget {+ const MobileShell({super.key, this.startError, this.onRetry, this.initialTab = MobileTab.records});++ /// Go 核心没能启动的原因+ final String? startError;+ final VoidCallback? onRetry;+ final MobileTab initialTab;++ @override+ State<MobileShell> createState() => _MobileShellState();+}++class _MobileShellState extends State<MobileShell> {+ late MobileTab _tab = widget.initialTab;+ bool _pairingDialogOpen = false;++ void select(MobileTab t) => setState(() => _tab = t);++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final l = context.l10n;++ // 对端发起配对时主动弹出指纹核对,和桌面一样(main.dart 的 Shell)+ final pending = state.pendingPairing;+ if (pending != null && !_pairingDialogOpen) {+ _pairingDialogOpen = true;+ WidgetsBinding.instance.addPostFrameCallback((_) async {+ if (!mounted) return;+ if (state.pendingPairing?.pairingSession != pending.pairingSession) {+ setState(() => _pairingDialogOpen = false);+ return;+ }+ await showPairingConfirmDialog(context, pending);+ if (mounted) setState(() => _pairingDialogOpen = false);+ });+ }++ final Widget body;+ if (widget.startError != null) {+ body = _StartFailed(error: widget.startError!, onRetry: widget.onRetry);+ } else if (state.link == LinkState.connecting && state.config == null) {+ body = const Center(child: CircularProgressIndicator(strokeWidth: 2.5));+ } else {+ body = IndexedStack(+ index: _tab.index,+ children: [+ const RecordsTab(),+ SendTab(onPair: () => select(MobileTab.devices)),+ const DevicesTab(),+ const SettingsTab(),+ ],+ );+ }++ return AnnotatedRegion<SystemUiOverlayStyle>(+ value: Theme.of(context).brightness == Brightness.dark ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark,+ child: Scaffold(+ body: body,+ bottomNavigationBar: MobileTabBar(+ index: _tab.index,+ onSelect: (i) => select(MobileTab.values[i]),+ items: [+ (FluentIcons.history_24_regular, FluentIcons.history_24_filled, l.mTabRecords),+ (FluentIcons.send_24_regular, FluentIcons.send_24_filled, l.mTabSend),+ (FluentIcons.laptop_24_regular, FluentIcons.laptop_24_filled, l.navDevices),+ (FluentIcons.settings_24_regular, FluentIcons.settings_24_filled, l.navSettings),+ ],+ ),+ ),+ );+ }+}++class _StartFailed extends StatelessWidget {+ const _StartFailed({required this.error, this.onRetry});++ final String error;+ final VoidCallback? onRetry;++ @override+ Widget build(BuildContext context) {+ final l = context.l10n;+ return SafeArea(+ child: Padding(+ padding: const EdgeInsets.all(Insets.xl),+ child: EmptyState(+ icon: AppIcons.exclamationmarkCircle,+ title: l.mStartFailed(error),+ action: FilledButton(onPressed: onRetry, child: Text(l.retry)),+ ),+ ),+ );+ }+}diff --git a/ui/lib/mobile/record_actions.dart b/ui/lib/mobile/record_actions.dartnew file mode 100644index 0000000..bd75b19--- /dev/null+++ b/ui/lib/mobile/record_actions.dart@@ -0,0 +1,72 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/pasteferry/v1/daemon.pb.dart';+import '../i18n.dart';+import '../main.dart' show AppScope;+import '../widgets/common.dart';+import 'host.dart';++/// 记录上的「复制 / 保存 / 分享」(design/phone-sync.md 3.2.2 节)。+///+/// 文字直接写剪贴板;图片和文件不在本机时(超过电脑的自动同步上限、或之前下载失败)先下载,+/// 下载时不动剪贴板(preserve_clipboard),下完再按用户点的那一项处理。+enum RecordAction { copy, save, share }++bool isMedia(ClipRecord r) => r.kind == ClipKind.CLIP_KIND_IMAGE || r.kind == ClipKind.CLIP_KIND_FILE;++Future<void> runRecordAction(BuildContext context, ClipRecord r, RecordAction action) async {+ final state = AppScope.read(context);+ final l = context.l10n;+ try {+ if (isMedia(r) && r.status != ClipStatus.CLIP_STATUS_READY) {+ if (r.status == ClipStatus.CLIP_STATUS_EXPIRED) {+ showToast(context, l.expired, error: true);+ return;+ }+ showToast(context, l.mDownloading);+ await _download(state, r.id);+ }+ switch (action) {+ case RecordAction.copy:+ await state.applyToClipboard(r.id);+ if (context.mounted) showToast(context, l.mCopied);+ case RecordAction.save:+ final paths = await _localPaths(state, r.id);+ await Host.save(paths);+ if (context.mounted) showToast(context, l.mSaved);+ case RecordAction.share:+ await Host.share(await _localPaths(state, r.id));+ }+ } catch (e) {+ if (context.mounted) showToast(context, l.mActionFailed(AppState.describeError(e)), error: true);+ }+}++Future<List<String>> _localPaths(AppState state, String id) async {+ final paths = await state.localPaths(id);+ if (paths.isEmpty) throw StateError(appL10n.expired);+ return paths;+}++/// 下载到本机、不写剪贴板,等记录变成「就绪」。+Future<void> _download(AppState state, String id) async {+ final done = Completer<void>();+ void check() {+ final r = state.recordById(id);+ if (r == null || done.isCompleted) return;+ if (r.status == ClipStatus.CLIP_STATUS_READY) done.complete();+ if (r.status == ClipStatus.CLIP_STATUS_FAILED) done.completeError(StateError(r.error));+ }++ state.addListener(check);+ try {+ await state.fetchImagePreview(id);+ check();+ await done.future;+ } finally {+ state.removeListener(check);+ }+}diff --git a/ui/lib/mobile/records_tab.dart b/ui/lib/mobile/records_tab.dartnew file mode 100644index 0000000..7322952--- /dev/null+++ b/ui/lib/mobile/records_tab.dart@@ -0,0 +1,502 @@+import 'dart:io';++import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/pasteferry/v1/daemon.pb.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart' show AppScope;+import '../records.dart';+import '../theme.dart';+import '../widgets/common.dart';+import 'ui.dart';+import 'record_actions.dart';++/// 复制记录(design/phone-sync.md 3.2.4 节):搜索、按类型筛选、列表;点开看详情,长按删除。+class RecordsTab extends StatefulWidget {+ const RecordsTab({super.key});++ @override+ State<RecordsTab> createState() => _RecordsTabState();+}++class _RecordsTabState extends State<RecordsTab> {+ RecordFilter _filter = RecordFilter.all;++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final l = context.l10n;+ final p = context.palette;+ final source = state.searching ? (state.searchResults ?? const <ClipRecord>[]) : state.records;+ final records = source.where(_filter.matches).toList();++ return SafeArea(+ bottom: false,+ child: CustomScrollView(+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,+ slivers: [+ SliverToBoxAdapter(child: MobileHeader(title: l.mTabRecords)),+ SliverToBoxAdapter(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.md),+ child: Column(+ children: [+ MobileSearchField(hint: l.searchHint, onChanged: state.search),+ const SizedBox(height: Insets.md),+ MobileSegmented<RecordFilter>(+ value: _filter,+ segments: [for (final f in RecordFilter.values) (f, f.label(l))],+ onChanged: (f) => setState(() => _filter = f),+ ),+ ],+ ),+ ),+ ),+ const SliverToBoxAdapter(child: LanNotice()),+ if (records.isEmpty)+ SliverFillRemaining(+ hasScrollBody: false,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, Insets.xl, Insets.xl, 96),+ child: EmptyState(+ icon: AppIcons.clock,+ title: state.searching+ ? l.searchEmptyTitle(state.searchQuery)+ : _filter == RecordFilter.all+ ? l.historyEmptyTitle+ : l.historyEmptyFilteredTitle,+ description: state.searching ? l.searchEmptyBody : l.historyEmptySubtitle,+ ),+ ),+ )+ else+ SliverPadding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.xl),+ sliver: DecoratedSliver(+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ sliver: SliverList.separated(+ itemCount: records.length,+ // 分隔线从文字处开始:左边距 16 + 图标 40 + 间距 12+ separatorBuilder: (_, _) => const Divider(indent: 68, height: 1),+ itemBuilder: (context, i) => _RecordRow(+ record: records[i],+ first: i == 0,+ last: i == records.length - 1,+ query: state.searching ? state.searchQuery : null,+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// 一行记录:左边类型图标(图片换成缩略图),中间内容与「来自 × · 大小 · 时间」,+/// 右边文字是「复制」,图片和文件是箭头(点开再复制、保存、分享)。和网页的一行一样。+class _RecordRow extends StatelessWidget {+ const _RecordRow({required this.record, required this.first, required this.last, this.query});++ final ClipRecord record;+ final bool first;+ final bool last;+ final String? query;++ @override+ Widget build(BuildContext context) {+ final r = record;+ final p = context.palette;+ final l = context.l10n;+ final state = AppScope.of(context);+ final note = statusNote(r);+ final progress = state.progressOf(r.id);+ final media = isMedia(r);+ return InkWell(+ borderRadius: BorderRadius.vertical(+ top: first ? const Radius.circular(Radii.lg) : Radius.zero,+ bottom: last ? const Radius.circular(Radii.lg) : Radius.zero,+ ),+ onTap: () => showRecordSheet(context, r),+ onLongPress: () => confirmDelete(context, r),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.sm, Insets.md),+ child: Row(+ children: [+ Align(alignment: Alignment.topCenter, child: RecordThumb(record: r)),+ const SizedBox(width: Insets.md),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ contentTitle(r, query: query),+ maxLines: media ? 1 : 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 15, height: 1.375),+ ),+ const SizedBox(height: 2),+ Text.rich(+ TextSpan(+ children: [+ TextSpan(+ text: recordSource(r),+ style: r.outgoing ? TextStyle(color: p.accent) : null,+ ),+ TextSpan(+ text: [+ if (r.totalSize > 0) humanBytes(r.totalSize.toInt()),+ relativeTime(recordTime(r)),+ ].map((e) => ' · $e').join(),+ ),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(fontSize: 13, color: p.textDim),+ ),+ if (note != null)+ Padding(+ padding: const EdgeInsets.only(top: 2),+ child: Text(+ note,+ style: TextStyle(+ fontSize: 13,+ color: r.status == ClipStatus.CLIP_STATUS_FAILED ? p.danger : p.textDim,+ ),+ ),+ ),+ if (r.status == ClipStatus.CLIP_STATUS_FETCHING) ...[+ const SizedBox(height: 6),+ LinearProgressIndicator(value: progress, minHeight: 3, borderRadius: BorderRadius.circular(2)),+ ],+ ],+ ),+ ),+ const SizedBox(width: Insets.xs),+ if (media)+ Padding(+ padding: const EdgeInsets.only(right: Insets.xs),+ child: Icon(AppIcons.chevronRight, size: 20, color: p.textFaint),+ )+ else+ TextButton(+ style: TextButton.styleFrom(+ minimumSize: const Size(0, 36),+ padding: const EdgeInsets.symmetric(horizontal: Insets.sm),+ textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),+ ),+ onPressed: () => runRecordAction(context, r, RecordAction.copy),+ child: Text(l.mCopy),+ ),+ ],+ ),+ ),+ );+ }+}++/// 列表里标题下面要补充的状态:还没下载、下载中、失败、过期。就绪时为 null+String? statusNote(ClipRecord r) {+ final l = appL10n;+ return switch (r.status) {+ ClipStatus.CLIP_STATUS_REMOTE_ONLY => l.mNotDownloaded,+ ClipStatus.CLIP_STATUS_FETCHING => l.mDownloading,+ ClipStatus.CLIP_STATUS_FAILED => l.transferFailed,+ ClipStatus.CLIP_STATUS_EXPIRED => l.expired,+ _ => null,+ };+}++/// 行首 40×40:图片显示缩略图,其他显示类型图标,和网页一样不加底色。+class RecordThumb extends StatelessWidget {+ const RecordThumb({super.key, required this.record, this.size = 40});++ final ClipRecord record;+ final double size;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final r = record;+ final image = r.status == ClipStatus.CLIP_STATUS_READY && r.imageCount > 0;+ final icon = Icon(kindIcon(r), size: 24, color: p.textDim);+ return SizedBox.square(+ dimension: size,+ child: ClipRRect(+ borderRadius: BorderRadius.circular(Radii.sm),+ child: image ? _Preview(clipId: r.id, fallback: Center(child: icon)) : Center(child: icon),+ ),+ );+ }+}++/// 记录里第一张图片。路径由 Go 核心给出(HEIC 之类先转成 PNG),按记录缓存+class _Preview extends StatelessWidget {+ const _Preview({required this.clipId, required this.fallback});++ final String clipId;+ final Widget fallback;++ static final _paths = <String, Future<String>>{};++ @override+ Widget build(BuildContext context) {+ final state = AppScope.read(context);+ final path = _paths.putIfAbsent(clipId, () => state.imagePreview(clipId).then((g) => g.path));+ return FutureBuilder<String>(+ future: path,+ builder: (context, snap) {+ if (snap.hasError) {+ _paths.remove(clipId);+ return fallback;+ }+ if (!snap.hasData) return fallback;+ return Image.file(+ File(snap.data!),+ fit: BoxFit.cover,+ cacheWidth: 160,+ errorBuilder: (_, _, _) => fallback,+ );+ },+ );+ }+}++Future<void> confirmDelete(BuildContext context, ClipRecord r) async {+ final l = context.l10n;+ final state = AppScope.read(context);+ final ok = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.mDeleteConfirm),+ content: Text(contentTitle(r), maxLines: 3, overflow: TextOverflow.ellipsis),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ TextButton(+ style: TextButton.styleFrom(foregroundColor: ctx.palette.danger),+ onPressed: () => Navigator.pop(ctx, true),+ child: Text(l.mDelete),+ ),+ ],+ ),+ );+ if (ok != true) return;+ try {+ await state.deleteRecords(ids: [r.id]);+ if (context.mounted) showToast(context, l.deleted);+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+}++/// 点开一条记录:全文、图片预览或文件列表,下面是「复制 / 保存 / 分享」。+Future<void> showRecordSheet(BuildContext context, ClipRecord r) => showModalBottomSheet<void>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ builder: (_) => _RecordSheet(id: r.id, initial: r),+);++class _RecordSheet extends StatelessWidget {+ const _RecordSheet({required this.id, required this.initial});++ final String id;+ final ClipRecord initial;++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final r = state.recordById(id) ?? initial;+ final l = context.l10n;+ final p = context.palette;+ final media = isMedia(r);+ final busy = r.status == ClipStatus.CLIP_STATUS_FETCHING;+ final note = statusNote(r);+ const buttonSize = Size(0, 44);++ return ConstrainedBox(+ constraints: BoxConstraints(maxHeight: MediaQuery.sizeOf(context).height * 0.85),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.lg),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Text(+ '${recordSource(r)} · ${relativeTime(recordTime(r))}',+ style: TextStyle(fontSize: 13, color: p.textDim),+ textAlign: TextAlign.center,+ ),+ const SizedBox(height: Insets.md),+ Flexible(+ child: SingleChildScrollView(+ child: media ? _MediaBody(record: r) : _FullText(record: r),+ ),+ ),+ if (note != null) ...[+ const SizedBox(height: Insets.md),+ Text(+ r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY ? '$note · ${l.mDownloadHint}' : note,+ style: TextStyle(fontSize: 13, color: p.textDim),+ textAlign: TextAlign.center,+ ),+ ],+ if (busy) ...[+ const SizedBox(height: Insets.sm),+ LinearProgressIndicator(value: state.progressOf(r.id), minHeight: 3),+ ],+ const SizedBox(height: Insets.lg),+ FilledButton.icon(+ style: FilledButton.styleFrom(minimumSize: buttonSize),+ onPressed: busy ? null : () => runRecordAction(context, r, RecordAction.copy),+ icon: Icon(AppIcons.copy, size: 20),+ label: Text(l.mCopy),+ ),+ if (media) ...[+ const SizedBox(height: Insets.md),+ Row(+ children: [+ Expanded(+ child: FilledButton.icon(+ style: secondaryButtonStyle(context).copyWith(minimumSize: const WidgetStatePropertyAll(buttonSize)),+ onPressed: busy ? null : () => runRecordAction(context, r, RecordAction.save),+ icon: Icon(AppIcons.download, size: 20),+ label: Text(l.save),+ ),+ ),+ const SizedBox(width: Insets.md),+ Expanded(+ child: FilledButton.icon(+ style: secondaryButtonStyle(context).copyWith(minimumSize: const WidgetStatePropertyAll(buttonSize)),+ onPressed: busy ? null : () => runRecordAction(context, r, RecordAction.share),+ icon: Icon(AppIcons.share, size: 20),+ label: Text(l.mShare),+ ),+ ),+ ],+ ),+ ],+ const SizedBox(height: Insets.xs),+ TextButton(+ style: TextButton.styleFrom(foregroundColor: p.danger),+ onPressed: () async {+ Navigator.pop(context);+ await confirmDelete(context, r);+ },+ child: Text(l.deleteRecord),+ ),+ ],+ ),+ ),+ );+ }+}++class _FullText extends StatelessWidget {+ const _FullText({required this.record});++ final ClipRecord record;++ @override+ Widget build(BuildContext context) {+ final state = AppScope.read(context);+ final l = context.l10n;+ final p = context.palette;+ return FutureBuilder<ClipDetail>(+ future: state.clipDetail(record.id),+ builder: (context, snap) {+ final d = snap.data;+ final text = d?.text ?? record.textPreview;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Container(+ padding: const EdgeInsets.all(Insets.md),+ decoration: BoxDecoration(color: p.fill, borderRadius: BorderRadius.circular(Radii.md)),+ child: SelectableText(text, style: const TextStyle(fontSize: 16, height: 1.6)),+ ),+ if (d != null && d.textLength > text.runes.length) ...[+ const SizedBox(height: Insets.sm),+ Text(l.mTextTruncated(text.runes.length, d.textLength), style: TextStyle(fontSize: 13, color: p.textDim)),+ ],+ ],+ );+ },+ );+ }+}++/// 图片和文件:有缩略图时放在上面,下面一组列出名字和大小,和网页的详情一样。+class _MediaBody extends StatelessWidget {+ const _MediaBody({required this.record});++ final ClipRecord record;++ @override+ Widget build(BuildContext context) {+ final r = record;+ final p = context.palette;+ final l = context.l10n;+ final items = r.kind == ClipKind.CLIP_KIND_IMAGE+ ? [ClipItem(name: l.imageRecord, size: r.totalSize)]+ : r.items;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (r.status == ClipStatus.CLIP_STATUS_READY && r.imageCount > 0) ...[+ Center(+ child: ClipRRect(+ borderRadius: BorderRadius.circular(Radii.md),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxHeight: 224),+ child: _Preview(clipId: r.id, fallback: const SizedBox.shrink()),+ ),+ ),+ ),+ const SizedBox(height: Insets.md),+ ],+ Container(+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ child: Column(+ children: [+ for (var i = 0; i < items.length; i++) ...[+ if (i > 0) const Divider(indent: Insets.lg, height: 1),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.lg, vertical: Insets.md),+ child: Row(+ children: [+ Icon(items[i].isDir ? AppIcons.folder : kindIcon(r), size: 22, color: p.textDim),+ const SizedBox(width: Insets.md),+ Expanded(+ child: Text(+ items[i].name,+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(fontSize: 15),+ ),+ ),+ if (items[i].size > 0)+ Text(humanBytes(items[i].size.toInt()), style: TextStyle(fontSize: 13, color: p.textDim)),+ ],+ ),+ ),+ ],+ ],+ ),+ ),+ ],+ );+ }+}diff --git a/ui/lib/mobile/send_tab.dart b/ui/lib/mobile/send_tab.dartnew file mode 100644index 0000000..d5acde7--- /dev/null+++ b/ui/lib/mobile/send_tab.dart@@ -0,0 +1,199 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../app_state.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart' show AppScope;+import '../theme.dart';+import '../widgets/common.dart';+import 'ui.dart';++/// 发送页(design/phone-sync.md 3.2.3 节):手机上的文字发给在线的设备。+///+/// Android 10 起后台读不到剪贴板,手机上复制的内容不会自动发出,要粘贴到这里。+/// 「粘贴剪贴板里的文字」只在剪贴板里有文字时出现:判断用的是 [Clipboard.hasStrings],+/// 只查剪贴板的类型,系统不会弹「已粘贴」的提示;点了才真正读取。+class SendTab extends StatefulWidget {+ const SendTab({super.key, this.onPair});++ /// 还没有配对的设备时,「去配对」切到设备页+ final VoidCallback? onPair;++ @override+ State<SendTab> createState() => _SendTabState();+}++class _SendTabState extends State<SendTab> with WidgetsBindingObserver {+ final _text = TextEditingController();+ bool _clipboardHasText = false;+ bool _sending = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _text.addListener(() => setState(() {}));+ _checkClipboard();+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ _text.dispose();+ super.dispose();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState s) {+ if (s == AppLifecycleState.resumed) _checkClipboard();+ }++ Future<void> _checkClipboard() async {+ final has = await Clipboard.hasStrings();+ if (mounted && has != _clipboardHasText) setState(() => _clipboardHasText = has);+ }++ Future<void> _paste() async {+ final data = await Clipboard.getData(Clipboard.kTextPlain);+ final text = data?.text ?? '';+ if (!mounted) return;+ if (text.isEmpty) {+ setState(() => _clipboardHasText = false);+ showToast(context, context.l10n.mClipboardNoText, error: true);+ return;+ }+ final v = _text.value;+ final start = v.selection.isValid ? v.selection.start : v.text.length;+ final end = v.selection.isValid ? v.selection.end : v.text.length;+ _text.value = TextEditingValue(+ text: v.text.replaceRange(start, end, text),+ selection: TextSelection.collapsed(offset: start + text.length),+ );+ }++ Future<void> _send() async {+ final text = _text.text;+ if (text.trim().isEmpty || _sending) return;+ final l = context.l10n;+ setState(() => _sending = true);+ try {+ await AppScope.read(context).submitText(text);+ _text.clear();+ if (mounted) showToast(context, l.mSent);+ } catch (e) {+ if (mounted) showToast(context, l.mSendFailed(AppState.describeError(e)), error: true);+ } finally {+ if (mounted) setState(() => _sending = false);+ }+ }++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final l = context.l10n;+ final p = context.palette;+ final online = state.peers.where((d) => d.online).map((d) => d.name).toList();+ final canSend = online.isNotEmpty && _text.text.trim().isNotEmpty && !_sending;++ return SafeArea(+ bottom: false,+ child: GestureDetector(+ // 点空白处收起键盘+ onTap: () => FocusScope.of(context).unfocus(),+ behavior: HitTestBehavior.translucent,+ child: ListView(+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,+ children: [+ MobileHeader(title: l.mSendTitle),+ const LanNotice(),+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.xl),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // 输入框和网页一样:白底圆角的一块,聚焦时边框变成强调色+ TextField(+ controller: _text,+ minLines: 6,+ maxLines: 12,+ keyboardType: TextInputType.multiline,+ textCapitalization: TextCapitalization.sentences,+ style: const TextStyle(fontSize: 16, height: 1.6),+ decoration: InputDecoration(+ hintText: l.mSendHint,+ fillColor: p.surface,+ border: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.lg),+ borderSide: BorderSide(color: p.border),+ ),+ enabledBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.lg),+ borderSide: BorderSide(color: p.border),+ ),+ focusedBorder: OutlineInputBorder(+ borderRadius: BorderRadius.circular(Radii.lg),+ borderSide: BorderSide(color: p.accent),+ ),+ contentPadding: const EdgeInsets.symmetric(horizontal: Insets.lg, vertical: Insets.md),+ ),+ ),+ const SizedBox(height: Insets.md),+ Row(+ children: [+ // 网页这里是「选择文件」;App 一期只发文字,换成「粘贴」:剪贴板里有文字时才能点+ Expanded(+ child: FilledButton.icon(+ style: secondaryButtonStyle(context),+ onPressed: _clipboardHasText ? _paste : null,+ icon: Icon(AppIcons.docOnClipboard, size: 20),+ label: Text(l.mPaste),+ ),+ ),+ const SizedBox(width: Insets.md),+ Expanded(+ child: FilledButton.icon(+ onPressed: canSend ? _send : null,+ icon: _sending+ ? const SizedBox.square(+ dimension: 18,+ child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),+ )+ : Icon(AppIcons.send, size: 20),+ label: Text(l.mSendAction),+ ),+ ),+ ],+ ),+ const SizedBox(height: Insets.md),+ if (state.peers.isEmpty)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ style: TextButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: Insets.xs)),+ onPressed: widget.onPair,+ child: Text(l.mNoPairedDevices),+ ),+ )+ else+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.xs),+ child: Text(+ online.isEmpty ? l.mNoOnlineDevices : l.mSendTo(online.join('、')),+ style: TextStyle(fontSize: 13, color: online.isEmpty ? p.warning : p.textDim),+ ),+ ),+ const SizedBox(height: Insets.sm),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.xs),+ child: Text(l.mSendFootnote, style: TextStyle(fontSize: 13, height: 1.5, color: p.textDim)),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/ui/lib/mobile/settings_tab.dart b/ui/lib/mobile/settings_tab.dartnew file mode 100644index 0000000..3fe3363--- /dev/null+++ b/ui/lib/mobile/settings_tab.dart@@ -0,0 +1,192 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:protobuf/protobuf.dart';++import '../app_state.dart';+import '../i18n.dart';+import '../main.dart' show AppScope;+import '../theme.dart';+import '../widgets/common.dart';+import 'host.dart';+import 'ui.dart';++/// 设置页:本机名称、收到文字后写不写剪贴板、后台保持连接与相关的系统权限、版本。+class SettingsTab extends StatefulWidget {+ const SettingsTab({super.key});++ @override+ State<SettingsTab> createState() => _SettingsTabState();+}++class _SettingsTabState extends State<SettingsTab> with WidgetsBindingObserver {+ bool? _keepAlive;+ String? _notifications;+ bool? _battery;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _refresh();+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState s) {+ // 从系统设置回来:权限可能变了+ if (s == AppLifecycleState.resumed) _refresh();+ }++ Future<void> _refresh() async {+ try {+ final keep = await Host.keepAlive();+ final notif = await Host.notifications();+ final battery = await Host.batteryUnrestricted();+ if (mounted) {+ setState(() {+ _keepAlive = keep;+ _notifications = notif;+ _battery = battery;+ });+ }+ } on MissingPluginException {+ // 测试里没有宿主+ }+ }++ Future<void> _rename() async {+ final state = AppScope.read(context);+ final l = context.l10n;+ final cfg = state.config;+ if (cfg == null) return;+ final controller = TextEditingController(text: cfg.deviceName);+ final name = await showDialog<String>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.deviceName),+ content: TextField(+ controller: controller,+ autofocus: true,+ maxLength: 40,+ onSubmitted: (v) => Navigator.pop(ctx, v),+ ),+ actions: [+ TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.cancel)),+ TextButton(onPressed: () => Navigator.pop(ctx, controller.text), child: Text(l.save)),+ ],+ ),+ );+ controller.dispose();+ final trimmed = name?.trim() ?? '';+ if (trimmed.isEmpty || trimmed == cfg.deviceName) return;+ try {+ await state.updateConfig(cfg.deepCopy()..deviceName = trimmed);+ if (mounted) showToast(context, l.deviceNameUpdated);+ } catch (e) {+ if (mounted) showToast(context, AppState.describeError(e), error: true);+ }+ }++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final l = context.l10n;+ final p = context.palette;+ final cfg = state.config;++ return SafeArea(+ bottom: false,+ child: ListView(+ children: [+ MobileHeader(title: l.navSettings),+ MobileGroup(+ children: [+ MobileTile(+ title: l.deviceName,+ subtitle: cfg?.deviceName ?? '',+ trailing: Icon(Icons.chevron_right, color: p.textFaint),+ onTap: _rename,+ ),+ ],+ ),+ MobileGroup(+ title: l.mSectionSync,+ children: [+ MobileTile(+ title: l.autoApply,+ subtitle: l.mAutoApplyDesc,+ trailing: Switch(+ value: cfg?.autoApplyToClipboard ?? true,+ onChanged: cfg == null+ ? null+ : (v) async {+ try {+ await state.updateConfig(cfg.deepCopy()..autoApplyToClipboard = v);+ } catch (e) {+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ }+ },+ ),+ ),+ ],+ ),+ MobileGroup(+ title: l.mSectionBackground,+ children: [+ MobileTile(+ title: l.mKeepAlive,+ subtitle: l.mKeepAliveDesc,+ trailing: Switch(+ value: _keepAlive ?? true,+ onChanged: _keepAlive == null+ ? null+ : (v) async {+ setState(() => _keepAlive = v);+ await Host.setKeepAlive(v);+ },+ ),+ ),+ MobileTile(+ title: l.mNotifications,+ subtitle: l.mNotificationsDesc,+ trailing: _notifications == 'granted'+ ? Text(l.mAllowed, style: context.text.bodySmall)+ : TextButton(+ onPressed: () async {+ final s = await Host.requestNotifications();+ if (mounted) setState(() => _notifications = s);+ },+ child: Text(l.mAllow),+ ),+ ),+ MobileTile(+ title: l.mBattery,+ subtitle: l.mBatteryDesc,+ trailing: _battery == true+ ? Text(l.mAllowed, style: context.text.bodySmall)+ : TextButton(onPressed: Host.requestBatteryUnrestricted, child: Text(l.mAllow)),+ ),+ ],+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xxl),+ child: Column(+ children: [+ const AppMark(size: 40),+ const SizedBox(height: Insets.sm),+ Text(l.appName, style: context.text.titleSmall),+ Text(l.mVersion(state.status?.version ?? ''), style: context.text.bodySmall),+ Text(l.aboutDesc, style: context.text.bodySmall),+ ],+ ),+ ),+ ],+ ),+ );+ }+}diff --git a/ui/lib/mobile/ui.dart b/ui/lib/mobile/ui.dartnew file mode 100644index 0000000..8e17430--- /dev/null+++ b/ui/lib/mobile/ui.dart@@ -0,0 +1,482 @@+import 'package:fluentui_system_icons/fluentui_system_icons.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../app_state.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart' show AppScope;+import '../theme.dart';+import 'host.dart';++/// 手机 App 的界面部件。样子与手机网页传输(web/phone/src/ui.tsx、App.tsx)一一对应,+/// 配色、圆角、间距用桌面的设计系统(theme.dart):两边只是功能多少不同,看起来是同一个产品。++/// 次要按钮:浅灰底、正文色,对应网页的 `Button kind="secondary"`。+ButtonStyle secondaryButtonStyle(BuildContext context) {+ final p = context.palette;+ return FilledButton.styleFrom(+ backgroundColor: p.fill,+ foregroundColor: p.text,+ disabledBackgroundColor: p.fill.withValues(alpha: 0.4),+ disabledForegroundColor: p.text.withValues(alpha: 0.4),+ textStyle: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500),+ );+}++/// 页头:上面一行是连接的电脑与状态,下面是大标题,对应网页的 header。+class MobileHeader extends StatelessWidget {+ const MobileHeader({super.key, required this.title, this.trailing});++ final String title;++ /// 右上角的圆形按钮+ final Widget? trailing;++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.lg, Insets.md),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ height: 36,+ child: Row(+ children: [+ const Expanded(child: ConnectionLine()),+ ?trailing,+ ],+ ),+ ),+ const SizedBox(height: Insets.sm),+ Text(title, style: context.text.headlineMedium),+ ],+ ),+ );+ }+}++/// 页头右上角 36×36 的圆形按钮,浅灰底。+class HeaderButton extends StatelessWidget {+ const HeaderButton({super.key, required this.icon, required this.tooltip, required this.onTap});++ final IconData icon;+ final String tooltip;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Tooltip(+ message: tooltip,+ child: Material(+ color: p.fill,+ shape: const CircleBorder(),+ child: InkWell(+ customBorder: const CircleBorder(),+ onTap: onTap,+ child: SizedBox.square(dimension: 36, child: Icon(icon, size: 20, color: p.text)),+ ),+ ),+ );+ }+}++/// 连接状态:电脑图标、在线的电脑名、状态点与文字。和网页页头第一行一样。+class ConnectionLine extends StatelessWidget {+ const ConnectionLine({super.key});++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final p = context.palette;+ final l = context.l10n;+ final online = state.peers.where((d) => d.online).map((d) => d.name).toList();+ final String? device = switch (state.link) {+ LinkState.online when online.isNotEmpty => online.join('、'),+ LinkState.online when state.peers.isNotEmpty => state.peers.first.name,+ _ => null,+ };+ final (color, status) = switch (state.link) {+ LinkState.connecting => (p.textDim, l.linkConnecting),+ LinkState.offline => (p.danger, state.error ?? l.linkServiceNotRunning),+ LinkState.online when online.isNotEmpty => (p.online, l.online),+ LinkState.online when state.peers.isEmpty => (p.textDim, l.mNoPairedDevices),+ LinkState.online => (p.textDim, l.offline),+ };+ return Row(+ children: [+ Icon(AppIcons.deviceLaptop, size: 18, color: p.textDim),+ const SizedBox(width: Insets.sm),+ if (device != null) ...[+ Flexible(+ child: Text(+ device,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: context.text.bodyMedium?.copyWith(fontSize: 14, fontWeight: FontWeight.w500),+ ),+ ),+ const SizedBox(width: Insets.sm),+ ],+ Container(width: 6, height: 6, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),+ const SizedBox(width: 6),+ Flexible(+ child: Text(+ status,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(fontSize: 13, color: color),+ ),+ ),+ ],+ );+ }+}++/// 搜索框:40 高、浅灰底,对应网页的 SearchField。+class MobileSearchField extends StatefulWidget {+ const MobileSearchField({super.key, required this.hint, required this.onChanged});++ final String hint;+ final ValueChanged<String> onChanged;++ @override+ State<MobileSearchField> createState() => _MobileSearchFieldState();+}++class _MobileSearchFieldState extends State<MobileSearchField> {+ final _controller = TextEditingController();++ @override+ void dispose() {+ _controller.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Container(+ height: 40,+ padding: const EdgeInsets.symmetric(horizontal: Insets.md),+ decoration: BoxDecoration(color: p.fill, borderRadius: BorderRadius.circular(Radii.md)),+ child: Row(+ children: [+ Icon(AppIcons.search, size: 18, color: p.textDim),+ const SizedBox(width: Insets.sm),+ Expanded(+ child: TextField(+ controller: _controller,+ onChanged: (v) {+ setState(() {});+ widget.onChanged(v);+ },+ textInputAction: TextInputAction.search,+ style: context.text.bodyLarge,+ decoration: InputDecoration(+ hintText: widget.hint,+ filled: false,+ isCollapsed: true,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ contentPadding: EdgeInsets.zero,+ ),+ ),+ ),+ if (_controller.text.isNotEmpty)+ GestureDetector(+ onTap: () {+ _controller.clear();+ setState(() {});+ widget.onChanged('');+ },+ child: Icon(FluentIcons.dismiss_circle_20_filled, size: 18, color: p.textFaint),+ ),+ ],+ ),+ );+ }+}++/// 分段选择:浅灰轨道,选中的一段是白底、加粗、带一点阴影,对应网页的 Segmented 与桌面的 Segmented。+class MobileSegmented<T> extends StatelessWidget {+ const MobileSegmented({super.key, required this.value, required this.segments, required this.onChanged});++ final T value;+ final List<(T, String)> segments;+ final ValueChanged<T> onChanged;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final dark = Theme.of(context).brightness == Brightness.dark;+ return Container(+ padding: const EdgeInsets.all(2),+ decoration: BoxDecoration(color: p.fill, borderRadius: BorderRadius.circular(Radii.md)),+ child: Row(+ children: [+ for (final (v, label) in segments)+ Expanded(+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => onChanged(v),+ child: AnimatedContainer(+ duration: const Duration(milliseconds: 150),+ height: 30,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: v == value ? (dark ? p.border : p.surface) : Colors.transparent,+ borderRadius: BorderRadius.circular(7),+ boxShadow: v == value+ ? const [BoxShadow(color: Color(0x14000000), blurRadius: 2, offset: Offset(0, 1))]+ : null,+ ),+ child: Text(+ label,+ maxLines: 1,+ style: TextStyle(+ fontSize: 13,+ fontWeight: v == value ? FontWeight.w600 : FontWeight.w400,+ color: v == value ? p.text : p.textDim,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );+ }+}++/// 白底圆角的一组,行与行之间是从文字处开始的分隔线,对应网页的 Group 与 Separator。+class MobileGroup extends StatelessWidget {+ const MobileGroup({super.key, required this.children, this.title, this.footer, this.inset = Insets.lg});++ final List<Widget> children;+ final String? title;+ final String? footer;++ /// 分隔线左边的缩进:行首有图标时对齐到文字+ final double inset;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.xl),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ if (title != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xs, 0, Insets.xs, Insets.sm),+ child: Text(title!, style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: p.textDim)),+ ),+ Container(+ clipBehavior: Clip.antiAlias,+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ child: Material(+ type: MaterialType.transparency,+ child: Column(+ children: [+ for (var i = 0; i < children.length; i++) ...[+ if (i > 0) Divider(indent: inset, height: 1),+ children[i],+ ],+ ],+ ),+ ),+ ),+ if (footer != null)+ Padding(+ padding: const EdgeInsets.fromLTRB(Insets.xs, Insets.sm, Insets.xs, 0),+ child: Text(footer!, style: context.text.bodySmall),+ ),+ ],+ ),+ );+ }+}++/// 组里的一行:标题、说明、右边的开关或按钮。+class MobileTile extends StatelessWidget {+ const MobileTile({super.key, required this.title, this.subtitle, this.trailing, this.leading, this.onTap});++ final String title;+ final String? subtitle;+ final Widget? trailing;+ final Widget? leading;+ final VoidCallback? onTap;++ @override+ Widget build(BuildContext context) {+ return InkWell(+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 52),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: Insets.lg, vertical: Insets.md),+ child: Row(+ children: [+ if (leading != null) ...[leading!, const SizedBox(width: Insets.md)],+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(title, style: context.text.bodyLarge?.copyWith(fontSize: 16, height: 1.35)),+ if (subtitle != null) ...[+ const SizedBox(height: 2),+ Text(subtitle!, style: context.text.bodySmall),+ ],+ ],+ ),+ ),+ if (trailing != null) ...[const SizedBox(width: Insets.md), trailing!],+ ],+ ),+ ),+ ),+ );+ }+}++/// 底部标签栏:半透明底、顶上一条细线,选中的标签换成实心图标、用强调色,对应网页的 TabBar。+class MobileTabBar extends StatelessWidget {+ const MobileTabBar({super.key, required this.index, required this.items, required this.onSelect});++ final int index;++ /// (线框图标, 实心图标, 文字)+ final List<(IconData, IconData, String)> items;+ final ValueChanged<int> onSelect;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ return DecoratedBox(+ decoration: BoxDecoration(+ color: p.background.withValues(alpha: 0.94),+ border: Border(top: BorderSide(color: p.border, width: 0.5)),+ ),+ child: SafeArea(+ top: false,+ child: SizedBox(+ height: 56,+ child: Row(+ children: [+ for (var i = 0; i < items.length; i++)+ Expanded(+ child: Semantics(+ button: true,+ selected: i == index,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: () => onSelect(i),+ child: Column(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Icon(i == index ? items[i].$2 : items[i].$1, size: 24, color: i == index ? p.accent : p.textDim),+ const SizedBox(height: 2),+ Text(+ items[i].$3,+ style: TextStyle(+ fontSize: 11,+ fontWeight: FontWeight.w500,+ color: i == index ? p.accent : p.textDim,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++/// 不在 Wi-Fi 上时页面顶部的提示:一期只在局域网里同步。+class LanNotice extends StatefulWidget {+ const LanNotice({super.key});++ @override+ State<LanNotice> createState() => _LanNoticeState();+}++class _LanNoticeState extends State<LanNotice> with WidgetsBindingObserver {+ bool _onLan = true;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ _check();+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ void didChangeAppLifecycleState(AppLifecycleState s) {+ if (s == AppLifecycleState.resumed) _check();+ }++ Future<void> _check() async {+ try {+ final on = await Host.onLan();+ if (mounted && on != _onLan) setState(() => _onLan = on);+ } on MissingPluginException {+ // 测试里没有宿主+ }+ }++ @override+ Widget build(BuildContext context) {+ if (_onLan) return const SizedBox.shrink();+ final l = context.l10n;+ final p = context.palette;+ return Padding(+ padding: const EdgeInsets.fromLTRB(Insets.lg, 0, Insets.lg, Insets.md),+ child: Container(+ padding: const EdgeInsets.all(Insets.lg),+ decoration: BoxDecoration(+ color: p.surface,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(AppIcons.wifiOff, size: 22, color: p.warning),+ const SizedBox(width: Insets.md),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(l.mNotOnLanTitle, style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600)),+ const SizedBox(height: 2),+ Text(l.mNotOnLanBody, style: context.text.bodySmall),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/ui/lib/pages/devices_page.dart b/ui/lib/pages/devices_page.dartindex 1701bc0..7c9e710 100644--- a/ui/lib/pages/devices_page.dart+++ b/ui/lib/pages/devices_page.dart@@ -9,6 +9,7 @@ import '../theme.dart';import '../widgets/common.dart';import '../widgets/nearby_dialog.dart';import '../widgets/pairing_dialog.dart';+import '../widgets/web_share.dart';import '../icons.dart';import '../platform.dart';@@ -102,6 +103,7 @@ class DevicesPage extends StatelessWidget {],),),+ const WebShareSection(),],),),@@ -223,6 +225,7 @@ String connectionLabel(Device d) => switch (d.connection) {IconData platformIcon(String platform) => switch (platform) {'windows' || 'linux' => AppIcons.desktopComputer,+ 'android' => AppIcons.phone,_ => AppIcons.deviceLaptop,};diff --git a/ui/lib/picker/picker_view.dart b/ui/lib/picker/picker_view.dartindex 2a3f063..95e2c98 100644--- a/ui/lib/picker/picker_view.dart+++ b/ui/lib/picker/picker_view.dart@@ -511,7 +511,7 @@ class _PickerRow extends StatelessWidget {final thumb = isImage ? state.thumbnailOf(r.id) : null;final meta = [if (r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY) humanBytes(r.totalSize.toInt()),- if (!r.outgoing) r.originDeviceName,+ if (!r.outgoing) r.originDeviceName else if (r.viaName.isNotEmpty) r.viaName,if (r.favorite) appL10n.favoritedAt(shortDate(favoritedTime(r))) else relativeTime(recordTime(r)),].join(' · ');diff --git a/ui/lib/platform.dart b/ui/lib/platform.dartindex 8f58dba..8bbfaac 100644--- a/ui/lib/platform.dart+++ b/ui/lib/platform.dart@@ -7,12 +7,20 @@ abstract final class Wording {static final bool _win = !Platform.isMacOS;/// 说到本机时的叫法,用作标题- static String get thisDevice => _win ? appL10n.thisPcTitle : appL10n.thisMacTitle;+ static String get thisDevice => Platform.isAndroid+ ? appL10n.mThisPhone+ : _win+ ? appL10n.thisPcTitle+ : appL10n.thisMacTitle;/// 用在句子中间。中日文里「Mac」后面紧跟汉字,文案里已带好空格- static String get thisDeviceInText => _win ? appL10n.thisPcInText : appL10n.thisMacInText;+ static String get thisDeviceInText => Platform.isAndroid+ ? appL10n.mThisPhone+ : _win+ ? appL10n.thisPcInText+ : appL10n.thisMacInText;- /// 说到配对双方时的叫法,用在句子中间:Windows 与 Linux 上对方可能是 Mac,也可能是另一台电脑+ /// 说到配对双方时的叫法,用在句子中间:Windows、Linux 与手机上对方可能是 Mac,也可能是另一台电脑static String get bothDevicesInText => _win ? appL10n.bothDevices : appL10n.bothMacs;}diff --git a/ui/lib/records.dart b/ui/lib/records.dartindex 34721a3..4a16c64 100644--- a/ui/lib/records.dart+++ b/ui/lib/records.dart@@ -67,7 +67,10 @@ String contentTitle(ClipRecord r, {String? query}) {}/// 记录的来源:本机,或者「来自」哪台设备。-String recordSource(ClipRecord r) => r.outgoing ? appL10n.thisDeviceShort : appL10n.fromDevice(r.originDeviceName);+// 手机网页传输发来的内容也是本机发出的(会同步给其他设备),来源写手机的名字+String recordSource(ClipRecord r) => r.outgoing+ ? (r.viaName.isNotEmpty ? appL10n.fromDevice(r.viaName) : appL10n.thisDeviceShort)+ : appL10n.fromDevice(r.originDeviceName);DateTime recordTime(ClipRecord r) => DateTime.fromMillisecondsSinceEpoch(r.createdAtUnix.toInt() * 1000);diff --git a/ui/lib/widgets/web_share.dart b/ui/lib/widgets/web_share.dartnew file mode 100644index 0000000..2ec8636--- /dev/null+++ b/ui/lib/widgets/web_share.dart@@ -0,0 +1,490 @@+import 'dart:async';+import 'dart:typed_data';++import 'package:flutter/material.dart';++import '../app_state.dart';+import '../gen/pasteferry/v1/daemon.pb.dart';+import '../i18n.dart';+import '../icons.dart';+import '../main.dart';+import '../theme.dart';+import 'common.dart';++/// 设备页里的「手机网页传输」:开关、显示二维码、已登记的手机(design/phone-sync.md 第 2 节)。+/// 旧版后台服务没有这个功能时不显示。+class WebShareSection extends StatelessWidget {+ const WebShareSection({super.key});++ @override+ Widget build(BuildContext context) {+ final state = AppScope.of(context);+ final st = state.webShare;+ if (st == null) return const SizedBox.shrink();+ final l = context.l10n;+ final p = context.palette;+ final error = st.enabled && !st.listening && st.error.isNotEmpty;++ return GroupSection(+ title: l.webShareTitle,+ footnote: l.webShareFootnote,+ child: GroupBox(+ dividerIndent: 52,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ Insets.lg,+ Insets.md,+ Insets.lg,+ Insets.md,+ ),+ child: Row(+ children: [+ Icon(AppIcons.phone, size: 22, color: p.textDim),+ const SizedBox(width: Insets.md + 2),+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(l.webShareSwitch, style: context.text.labelLarge),+ const SizedBox(height: 2),+ Text(+ error+ ? l.webShareNotListening(st.error)+ : st.enabled+ ? l.webShareOn(st.sessions.length)+ : l.webShareOff,+ style: context.text.bodySmall?.copyWith(+ color: error ? p.danger : null,+ ),+ ),+ ],+ ),+ ),+ if (st.listening) ...[+ OutlinedButton.icon(+ onPressed: () => showWebShareDialog(context),+ icon: Icon(AppIcons.qrCode, size: 14),+ label: Text(l.webShareShowQr),+ ),+ const SizedBox(width: Insets.md),+ ],+ SmallSwitch(+ value: st.enabled,+ onChanged: (v) async {+ try {+ await AppScope.read(context).setWebShare(v);+ // 刚打开时直接给出二维码,省得再点一次+ if (v &&+ context.mounted &&+ (AppScope.read(context).webShare?.listening ??+ false)) {+ unawaited(showWebShareDialog(context));+ }+ } catch (e) {+ if (context.mounted) {+ showToast(context, AppState.describeError(e), error: true);+ }+ }+ },+ ),+ ],+ ),+ ),+ for (final s in st.sessions) _SessionRow(session: s),+ ],+ ),+ );+ }+}++class _SessionRow extends StatelessWidget {+ const _SessionRow({required this.session});++ final WebSession session;++ @override+ Widget build(BuildContext context) {+ final p = context.palette;+ final l = context.l10n;+ final lastSeen = DateTime.fromMillisecondsSinceEpoch(+ session.lastSeenUnix.toInt() * 1000,+ );+ return Padding(+ padding: const EdgeInsets.fromLTRB(+ 52,+ Insets.sm + 2,+ Insets.sm,+ Insets.sm + 2,+ ),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ session.name,+ style: context.text.bodyMedium?.copyWith(color: p.text),+ ),+ Text(+ l.webShareLastUsed(relativeTime(lastSeen)),+ style: context.text.bodySmall,+ ),+ ],+ ),+ ),+ TextButton(+ onPressed: () async {+ try {+ await AppScope.read(context).removeWebSession(session.id);+ if (context.mounted) {+ showToast(context, l.webShareRemoved(session.name));+ }+ } catch (e) {+ if (context.mounted) {+ showToast(context, AppState.describeError(e), error: true);+ }+ }+ },+ child: Text(l.webShareRemove),+ ),+ ],+ ),+ );+ }+}++Future<void> showWebShareDialog(BuildContext context) =>+ showDialog<void>(context: context, builder: (_) => const WebShareDialog());++/// 二维码窗口:手机扫码后在浏览器里打开网页。一张二维码只登记一台手机,+/// 被用掉、过期或换了地址时自动换一张;窗口关掉时作废还没被用过的那张。+class WebShareDialog extends StatefulWidget {+ const WebShareDialog({super.key});++ @override+ State<WebShareDialog> createState() => _WebShareDialogState();+}++class _WebShareDialogState extends State<WebShareDialog> {+ WebShareInvite? _invite;+ String _address = '';+ String? _error;+ bool _refreshing = false;+ Timer? _expiry;+ StreamSubscription<String>? _used;+ late final AppState _state = AppScope.read(context);++ @override+ void initState() {+ super.initState();+ _used = _state.webShareInviteUsed.listen((id) {+ if (id != _invite?.id) return;+ // 扫码登记的那台手机排在列表第一个(按最后使用时间倒序)+ final name = _state.webShare?.sessions.firstOrNull?.name;+ if (mounted && name != null) {+ showToast(context, context.l10n.webShareNewPhone(name));+ }+ _refresh(closeOld: false);+ });+ _refresh();+ }++ @override+ void dispose() {+ _expiry?.cancel();+ _used?.cancel();+ final id = _invite?.id;+ if (id != null) _state.closeWebShareInvite(id);+ super.dispose();+ }++ Future<void> _refresh({bool closeOld = true}) async {+ if (_refreshing) return;+ _refreshing = true;+ final old = _invite?.id;+ try {+ final inv = await _state.newWebShareInvite(_address);+ if (!mounted) {+ _state.closeWebShareInvite(inv.id);+ return;+ }+ setState(() {+ _invite = inv;+ _error = null;+ });+ if (closeOld && old != null) _state.closeWebShareInvite(old);+ // 到期前半分钟换新,窗口开着时二维码一直能用+ _expiry?.cancel();+ final left =+ DateTime.fromMillisecondsSinceEpoch(+ inv.expiresAtUnix.toInt() * 1000,+ ).difference(DateTime.now()) -+ const Duration(seconds: 30);+ _expiry = Timer(+ left.isNegative ? const Duration(seconds: 5) : left,+ _refresh,+ );+ } catch (e) {+ if (mounted) setState(() => _error = AppState.describeError(e));+ } finally {+ _refreshing = false;+ }+ }++ @override+ Widget build(BuildContext context) {+ final st = AppScope.of(context).webShare;+ final l = context.l10n;+ final p = context.palette;+ final addresses = st?.addresses ?? const <String>[];+ // 地址变了(换了 Wi-Fi):当前二维码里的地址不在了,换一张+ final current = _invite == null ? null : Uri.tryParse(_invite!.url)?.host;+ if (current != null &&+ addresses.isNotEmpty &&+ !addresses.contains(current) &&+ !_refreshing) {+ _address = '';+ WidgetsBinding.instance.addPostFrameCallback((_) => _refresh());+ }++ return Dialog(+ child: SizedBox(+ width: 420,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ Insets.xl,+ Insets.lg,+ Insets.md,+ Insets.xl,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Row(+ children: [+ Expanded(+ child: Text(+ l.webShareDialogTitle,+ style: context.text.titleMedium,+ ),+ ),+ IconAction(+ icon: AppIcons.xmark,+ tooltip: l.close,+ onTap: () => Navigator.pop(context),+ ),+ ],+ ),+ Padding(+ padding: const EdgeInsets.only(right: Insets.md),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const SizedBox(height: Insets.sm),+ Text(+ l.webShareDialogBody,+ style: context.text.bodyMedium?.copyWith(+ color: p.textDim,+ ),+ ),+ const SizedBox(height: Insets.lg),+ Center(+ child: Container(+ width: 232,+ height: 232,+ padding: const EdgeInsets.all(Insets.md),+ // 二维码一律深色画在白底上:深色模式下也是,反色的码很多扫码器认不出+ decoration: BoxDecoration(+ color: Colors.white,+ borderRadius: BorderRadius.circular(Radii.lg),+ border: Border.all(color: p.border),+ ),+ child: _invite == null+ ? Center(+ child: _error == null+ ? const SizedBox(+ width: 20,+ height: 20,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ ),+ )+ : Text(+ _error!,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ color: p.danger,+ ),+ ),+ )+ : QrCodeView(+ size: _invite!.qrSize,+ modules: Uint8List.fromList(_invite!.qrModules),+ ),+ ),+ ),+ const SizedBox(height: Insets.md),+ if (_invite != null)+ SelectableText(+ _invite!.url.split('#').first,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ fontFamily: monoFamily,+ ),+ ),+ if (addresses.length > 1) ...[+ const SizedBox(height: Insets.md),+ Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ Text(+ l.webShareAddress,+ style: context.text.bodySmall,+ ),+ const SizedBox(width: Insets.sm),+ DropdownButton<String>(+ value: addresses.contains(current)+ ? current+ : addresses.first,+ isDense: true,+ underline: const SizedBox.shrink(),+ style: context.text.bodySmall?.copyWith(+ color: p.text,+ fontFamily: monoFamily,+ ),+ items: [+ for (final a in addresses)+ DropdownMenuItem(value: a, child: Text(a)),+ ],+ onChanged: (a) {+ if (a == null || a == current) return;+ setState(() => _address = a);+ _refresh();+ },+ ),+ ],+ ),+ ] else if (addresses.isEmpty) ...[+ const SizedBox(height: Insets.sm),+ Text(+ l.webShareNoAddress,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ color: p.warning,+ ),+ ),+ ],+ if (st?.portFallback ?? false) ...[+ const SizedBox(height: Insets.sm),+ Text(+ l.webSharePortFallback,+ textAlign: TextAlign.center,+ style: context.text.bodySmall?.copyWith(+ color: p.warning,+ ),+ ),+ ],+ const SizedBox(height: Insets.lg),+ _Note(icon: AppIcons.lockShield, text: l.webShareSecurity),+ const SizedBox(height: Insets.sm),+ _Note(icon: AppIcons.info, text: l.webShareCantOpen),+ ],+ ),+ ),+ ],+ ),+ ),+ ),+ );+ }+}++class _Note extends StatelessWidget {+ const _Note({required this.icon, required this.text});++ final IconData icon;+ final String text;++ @override+ Widget build(BuildContext context) {+ return Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Icon(icon, size: 15, color: context.palette.textDim),+ const SizedBox(width: Insets.sm),+ Expanded(child: Text(text, style: context.text.bodySmall)),+ ],+ );+ }+}++/// 按后台服务给的点阵画二维码(internal/qrcode)。四周留 4 个模块的空白,这是扫码器要求的静区。+class QrCodeView extends StatelessWidget {+ const QrCodeView({+ super.key,+ required this.size,+ required this.modules,+ this.color = Colors.black,+ });++ final int size;+ final Uint8List modules;+ final Color color;++ @override+ Widget build(BuildContext context) => CustomPaint(+ painter: _QrPainter(size, modules, color),+ child: const SizedBox.expand(),+ );+}++class _QrPainter extends CustomPainter {+ _QrPainter(this.n, this.modules, this.color);++ final int n;+ final Uint8List modules;+ final Color color;++ static const quiet = 4;++ @override+ void paint(Canvas canvas, Size size) {+ if (n <= 0 || modules.length != n * n) return;+ final total = n + quiet * 2;+ // 每个模块取整数像素,边缘不会糊+ final cell = (size.shortestSide / total).floorToDouble().clamp(+ 1.0,+ double.infinity,+ );+ final origin = Offset(+ (size.width - cell * n) / 2,+ (size.height - cell * n) / 2,+ );+ final paint = Paint()+ ..color = color+ ..isAntiAlias = false;+ final path = Path();+ for (var y = 0; y < n; y++) {+ for (var x = 0; x < n; x++) {+ if (modules[y * n + x] == 1) {+ path.addRect(+ Rect.fromLTWH(+ origin.dx + x * cell,+ origin.dy + y * cell,+ cell,+ cell,+ ),+ );+ }+ }+ }+ canvas.drawPath(path, paint);+ }++ @override+ bool shouldRepaint(_QrPainter old) =>+ old.modules != modules || old.color != color || old.n != n;+}diff --git a/ui/test/mobile_test.dart b/ui/test/mobile_test.dartnew file mode 100644index 0000000..5e19e4f--- /dev/null+++ b/ui/test/mobile_test.dart@@ -0,0 +1,140 @@+import 'package:fixnum/fixnum.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:pasteferry_ui/app_state.dart';+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';+import 'package:pasteferry_ui/mobile/mobile_app.dart';+import 'package:pasteferry_ui/mobile/ui.dart';++Int64 _ago(int seconds) => Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000 - seconds);++/// 记下手机界面调了哪些操作,不连 Go 核心+class _PhoneState extends AppState {+ final submitted = <String>[];+ final applied = <String>[];++ @override+ Future<ClipRecord> submitText(String text) async {+ submitted.add(text);+ return ClipRecord(id: 'new', kind: ClipKind.CLIP_KIND_TEXT, outgoing: true, textPreview: text);+ }++ @override+ Future<void> applyToClipboard(String clipId) async => applied.add(clipId);+}++_PhoneState _demo({bool online = true, List<ClipRecord> records = const []}) {+ final state = _PhoneState();+ state.debugSeed(+ status: Status(version: '2.7.0'),+ config: Config(language: 'zh-Hans', deviceName: 'Pixel 8', autoApplyToClipboard: true),+ self: Device(id: 'self', name: 'Pixel 8', platform: 'android'),+ peers: [Device(id: 'mac', name: 'MacBook', platform: 'darwin', online: online)],+ records: records,+ );+ return state;+}++final _text = ClipRecord(+ id: 't1',+ kind: ClipKind.CLIP_KIND_TEXT,+ status: ClipStatus.CLIP_STATUS_READY,+ originDeviceName: 'MacBook',+ textPreview: '会议改到下午三点',+ createdAtUnix: _ago(60),+);++final _bigFile = ClipRecord(+ id: 'f1',+ kind: ClipKind.CLIP_KIND_FILE,+ status: ClipStatus.CLIP_STATUS_REMOTE_ONLY,+ originDeviceName: 'MacBook',+ items: [ClipItem(name: '演示视频.mov', size: Int64(80 << 20))],+ totalSize: Int64(80 << 20),+ createdAtUnix: _ago(120),+);++Future<void> _pump(WidgetTester tester, AppState state) async {+ tester.view.physicalSize = const Size(412 * 3, 915 * 3);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ await tester.pumpWidget(MobileApp(state: state));+ await tester.pumpAndSettle();+}++void main() {+ testWidgets('底部四个标签,默认是记录', (tester) async {+ await _pump(tester, _demo(records: [_text]));+ expect(find.byType(MobileTabBar), findsOneWidget);+ for (final label in ['记录', '发送', '设备', '设置']) {+ expect(find.descendant(of: find.byType(MobileTabBar), matching: find.text(label)), findsOneWidget);+ }+ expect(find.text('会议改到下午三点'), findsOneWidget);+ });++ testWidgets('记录上的「复制」写手机剪贴板;文字记录没有保存和分享', (tester) async {+ final state = _demo(records: [_text]);+ await _pump(tester, state);+ await tester.tap(find.widgetWithText(TextButton, '复制'));+ await tester.pump();+ expect(state.applied, ['t1']);+ await tester.pump(const Duration(seconds: 4));++ await tester.tap(find.text('会议改到下午三点'));+ await tester.pumpAndSettle();+ expect(find.widgetWithText(FilledButton, '复制'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, '保存'), findsNothing);+ expect(find.widgetWithText(FilledButton, '分享'), findsNothing);+ });++ testWidgets('没下载的文件标出来,详情里有复制、保存、分享', (tester) async {+ await _pump(tester, _demo(records: [_bigFile]));+ expect(find.textContaining('还没下载'), findsOneWidget);+ await tester.tap(find.text('演示视频.mov'));+ await tester.pumpAndSettle();+ expect(find.widgetWithText(FilledButton, '复制'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, '保存'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, '分享'), findsOneWidget);+ expect(find.textContaining('点「复制」「保存」「分享」时会先下载。'), findsOneWidget);+ });++ testWidgets('发送页:有在线设备、输入了文字才能发;发出后清空', (tester) async {+ final state = _demo();+ await _pump(tester, state);+ await tester.tap(find.descendant(of: find.byType(MobileTabBar), matching: find.text('发送')));+ await tester.pumpAndSettle();++ FilledButton send() => tester.widget<FilledButton>(find.widgetWithText(FilledButton, '发送'));+ expect(send().onPressed, isNull);+ expect(find.text('将发给 MacBook'), findsOneWidget);++ await tester.enterText(find.byType(TextField), '手机上写的一段话');+ await tester.pump();+ expect(send().onPressed, isNotNull);+ await tester.tap(find.widgetWithText(FilledButton, '发送'));+ await tester.pump();+ expect(state.submitted, ['手机上写的一段话']);+ expect(find.text('手机上写的一段话'), findsNothing);+ await tester.pump(const Duration(seconds: 4));+ });++ testWidgets('发送页:没有在线设备时不能发', (tester) async {+ await _pump(tester, _demo(online: false));+ await tester.tap(find.descendant(of: find.byType(MobileTabBar), matching: find.text('发送')));+ await tester.pumpAndSettle();+ await tester.enterText(find.byType(TextField), '你好');+ await tester.pump();+ expect(tester.widget<FilledButton>(find.widgetWithText(FilledButton, '发送')).onPressed, isNull);+ expect(find.text('附近没有在线的设备'), findsWidgets);+ });++ testWidgets('设备页列出已配对的设备,有添加设备和搜索附近设备', (tester) async {+ await _pump(tester, _demo());+ await tester.tap(find.descendant(of: find.byType(MobileTabBar), matching: find.text('设备')));+ await tester.pumpAndSettle();+ expect(find.text('MacBook'), findsWidgets);+ expect(find.text('添加设备'), findsOneWidget);+ expect(find.text('搜索附近设备'), findsOneWidget);+ });+}diff --git a/ui/test/web_share_test.dart b/ui/test/web_share_test.dartnew file mode 100644index 0000000..f45f414--- /dev/null+++ b/ui/test/web_share_test.dart@@ -0,0 +1,195 @@+import 'dart:typed_data';++import 'package:fixnum/fixnum.dart';+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:pasteferry_ui/app_state.dart';+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';+import 'package:pasteferry_ui/i18n.dart';+import 'package:pasteferry_ui/main.dart';+import 'package:pasteferry_ui/records.dart';+import 'package:pasteferry_ui/widgets/web_share.dart';++Int64 _now([int ago = 0]) => Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000 - ago);++/// 21×21 的点阵:左上角一个定位图案,够界面画出来就行+List<int> _modules() {+ final m = List<int>.filled(21 * 21, 0);+ for (var i = 0; i < 7; i++) {+ m[i] = 1;+ m[i * 21] = 1;+ }+ return m;+}++/// 记下界面调了哪些网页传输的操作,不连后台服务+class _WebShareState extends AppState {+ final invites = <String>[]; // 申请二维码时给的地址+ final closed = <String>[];+ final toggles = <bool>[];+ final removed = <String>[];+ var _serial = 0;++ WebShareStatus _status(bool on, {List<WebSession> sessions = const []}) => WebShareStatus(+ enabled: on,+ listening: on,+ port: 8790,+ addresses: ['192.168.1.5', '10.0.0.8'],+ sessions: sessions,+ );++ @override+ Future<WebShareInvite> newWebShareInvite(String address) async {+ invites.add(address);+ _serial++;+ final host = address.isEmpty ? '192.168.1.5' : address;+ return WebShareInvite(+ id: 'inv$_serial',+ url: 'http://$host:8790/#i=inv$_serial&k=key',+ expiresAtUnix: _now(-600),+ qrSize: 21,+ qrModules: _modules(),+ );+ }++ @override+ Future<void> closeWebShareInvite(String id) async => closed.add(id);++ @override+ Future<void> setWebShare(bool enabled) async {+ toggles.add(enabled);+ debugEvent(Event(webShareChanged: _status(enabled, sessions: webShare?.sessions ?? const [])));+ }++ @override+ Future<void> removeWebSession(String id) async {+ removed.add(id);+ debugEvent(Event(+ webShareChanged: _status(true, sessions: webShare!.sessions.where((s) => s.id != id).toList()),+ ));+ }+}++_WebShareState _demo({bool on = true, List<WebSession> sessions = const []}) {+ final state = _WebShareState();+ state.debugSeed(+ status: Status(version: '2.7.0'),+ config: Config(language: 'zh-Hans', deviceName: 'MacBook Pro'),+ self: Device(id: 'self', name: 'MacBook Pro', platform: 'darwin'),+ webShare: state._status(on, sessions: sessions),+ );+ return state;+}++final _iphone = WebSession(id: 's1', name: 'iPhone', createdAtUnix: _now(7200), lastSeenUnix: _now(120));++void main() {+ setUp(() {+ final view = TestWidgetsFlutterBinding.instance.platformDispatcher.views.first;+ view.physicalSize = const Size(1180, 900);+ view.devicePixelRatio = 1;+ });+ tearDown(() => TestWidgetsFlutterBinding.instance.platformDispatcher.views.first.reset());++ Future<AppLocalizations> openDevices(WidgetTester tester, AppState state) async {+ await tester.pumpWidget(PasteFerryApp(state: state));+ await tester.pump();+ final l = AppLocalizations.of(tester.element(find.byType(Shell)));+ await tester.tap(find.text(l.navDevices).first);+ await tester.pumpAndSettle();+ return l;+ }++ testWidgets('设备页:网页传输的开关、已登记的手机、移除', (tester) async {+ final state = _demo(sessions: [_iphone]);+ final l = await openDevices(tester, state);+ expect(find.text(l.webShareTitle), findsOneWidget);+ expect(find.text(l.webShareOn(1)), findsOneWidget);+ expect(find.text('iPhone'), findsOneWidget);+ expect(find.text(l.webShareShowQr), findsOneWidget);++ await tester.tap(find.text(l.webShareRemove));+ await tester.pumpAndSettle();+ expect(state.removed, ['s1']);+ expect(find.text('iPhone'), findsNothing);+ expect(find.text(l.webShareOn(0)), findsOneWidget);+ });++ testWidgets('关着时没有二维码按钮;打开开关后直接弹出二维码', (tester) async {+ final state = _demo(on: false);+ final l = await openDevices(tester, state);+ expect(find.text(l.webShareOff), findsOneWidget);+ expect(find.text(l.webShareShowQr), findsNothing);++ await tester.tap(find.byType(Switch).last);+ await tester.pumpAndSettle();+ expect(state.toggles, [true]);+ expect(find.byType(WebShareDialog), findsOneWidget);+ expect(find.byType(QrCodeView), findsOneWidget);+ expect(find.text('http://192.168.1.5:8790/'), findsOneWidget);+ });++ testWidgets('二维码窗口:被扫码用掉后换一张新的,切换地址,关掉时作废', (tester) async {+ final state = _demo(sessions: [_iphone]);+ final l = await openDevices(tester, state);+ await tester.tap(find.text(l.webShareShowQr));+ await tester.pumpAndSettle();+ expect(state.invites, ['']);++ // 手机扫码登记:后台服务推来 invite_used,窗口换一张新的二维码并提示+ final android = WebSession(id: 's2', name: 'Android 手机', createdAtUnix: _now(), lastSeenUnix: _now());+ state.debugEvent(Event(+ webShareChanged: WebShareStatus(+ enabled: true,+ listening: true,+ port: 8790,+ addresses: ['192.168.1.5', '10.0.0.8'],+ sessions: [android, _iphone],+ inviteUsed: 'inv1',+ ),+ ));+ await tester.pumpAndSettle();+ expect(state.invites, ['', '']);+ expect(find.text(l.webShareNewPhone('Android 手机')), findsOneWidget);+ expect(state.closed, isEmpty, reason: '用掉的那张不用再作废');++ // 换一个地址:用新地址申请,旧的作废+ await tester.tap(find.text('192.168.1.5').last);+ await tester.pumpAndSettle();+ await tester.tap(find.text('10.0.0.8').last);+ await tester.pumpAndSettle();+ expect(state.invites.last, '10.0.0.8');+ expect(state.closed, ['inv2']);+ expect(find.text('http://10.0.0.8:8790/'), findsOneWidget);++ await tester.tap(find.byTooltip(l.close));+ await tester.pumpAndSettle();+ expect(find.byType(WebShareDialog), findsNothing);+ expect(state.closed, ['inv2', 'inv3']);+ });++ testWidgets('旧版后台服务没有网页传输时不显示', (tester) async {+ final state = _WebShareState()+ ..debugSeed(+ status: Status(version: '2.6.3'),+ config: Config(language: 'zh-Hans'),+ self: Device(id: 'self', name: 'MacBook Pro', platform: 'darwin'),+ );+ final l = await openDevices(tester, state);+ expect(find.text(l.webShareTitle), findsNothing);+ });++ test('网页发来的记录显示手机的名字', () {+ final r = ClipRecord(outgoing: true, viaName: 'iPhone', originDeviceName: 'MacBook Pro');+ expect(recordSource(r), appL10n.fromDevice('iPhone'));+ expect(recordSource(ClipRecord(outgoing: true)), appL10n.thisDeviceShort);+ });++ testWidgets('二维码按点阵画出来', (tester) async {+ await tester.pumpWidget(MaterialApp(+ home: Center(child: SizedBox(width: 200, height: 200, child: QrCodeView(size: 21, modules: Uint8List.fromList(_modules())))),+ ));+ expect(find.byType(CustomPaint), findsWidgets);+ });+}diff --git a/ui/tool/screenshots/screenshots_test.dart b/ui/tool/screenshots/screenshots_test.dartindex a1cdadd..c81a292 100644--- a/ui/tool/screenshots/screenshots_test.dart+++ b/ui/tool/screenshots/screenshots_test.dart@@ -25,6 +25,7 @@ import 'package:pasteferry_ui/widgets/friends_dialog.dart';import 'package:pasteferry_ui/widgets/nearby_dialog.dart';import 'package:pasteferry_ui/widgets/pairing_dialog.dart';import 'package:pasteferry_ui/widgets/send_dialog.dart';+import 'package:pasteferry_ui/widgets/web_share.dart';import 'package:fixnum/fixnum.dart';import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';@@ -48,7 +49,22 @@ final _cjk = switch (_lang) {};/// 生成配对码、搜索附近设备、搜索复制记录都不走后台服务,直接给固定的演示数据。+/// 手机网页传输二维码的演示点阵(41×41),由 client-core/internal/qrcode 对一个演示网址生成+const _demoQr = '1111111001111110001101110101011100111111110000010100110110101001100110011001000001101110100001100100010110101110011010111011011101000000001010101100111111100101110110111010110000101001101001000100001011101100000100000011111011101110101010010000011111111010101010101010101010101010111111100000000011001001101010011000110000000000101010100000101101100110011101100000100101101000110111111110000100100001000110110001100010000010010100001011001100001010111101110001000111001010100011011010001100011110111010001011110111000100111010110101100111001101101100101110100001010101000111010001111000001101111110011001100001011111001010100100000010011110101111001111000000000010010110110001100010010001001101001001010011001001100011101110111000111001011100111111101111010000100010110010101110110111101000011001001011011010101100101000101111110001010100011010010101101010110001000010001000111000110100010111010100001110100010001001100100111011001110100111111000101000101010101111101010111001000010100101011011111001011001100110011001111100101101000011001110000011000100100001000011111011100000100101100110100000000110001111010100011001000011011101111011010000001110000011101111010110000110001101111011011001000001000111111110011100110111010010001000011000111010100001111100000011001001101101100100011000101010011010101101111000100001100001101101100111011101001111110100000000011100001111010101110011010001101111111110000111010010010011101010101011011100000100111110011101001111101001000100011011101010010111101010000010010011111100110111010001011110110100011011000110011011101110101111111100000010101011001001111111000001001100101010101011111010001010001011111110111101100111011111110111100110011';+class _DemoState extends AppState {+ @override+ Future<WebShareInvite> newWebShareInvite(String address) async => WebShareInvite(+ id: 'demo',+ url: 'http://192.168.1.20:8790/#i=demo',+ expiresAtUnix: Int64(DateTime.now().add(const Duration(minutes: 10)).millisecondsSinceEpoch ~/ 1000),+ qrSize: 41,+ qrModules: [for (final c in _demoQr.codeUnits) c - 48],+ );++ @override+ Future<void> closeWebShareInvite(String id) async {}+@overrideFuture<PairingCode> createPairingCode() async => (code: 'K7MP2X', addresses: ['192.168.1.20']);@@ -666,6 +682,32 @@ void main() {await _shoot(tester, 'devices', state: _demo(), section: Section.devices);});+ // 手机网页传输:设备页里的开关与已登记的手机,加上二维码窗口+ for (final dark in [false, true]) {+ testWidgets(dark ? 'web-share-dark' : 'web-share', (tester) async {+ // 在演示数据上加手机网页传输的状态:已配对的设备照常显示+ final state = _demo();+ state.debugSeed(+ status: state.status!,+ config: state.config!,+ self: state.self!,+ peers: state.peers,+ webShare: WebShareStatus(enabled: true, listening: true, port: 8790, addresses: [+ '192.168.1.20'+ ], sessions: [+ WebSession(id: 's1', name: 'iPhone', createdAtUnix: _ago(const Duration(days: 2)), lastSeenUnix: _ago(const Duration(minutes: 3))),+ ]),+ );+ await _shoot(tester, dark ? 'web-share-dark' : 'web-share',+ state: state,+ section: Section.devices,+ brightness: dark ? Brightness.dark : Brightness.light,+ window: const Size(960, 720), arrange: () async {+ showWebShareDialog(tester.element(find.byType(Shell)));+ });+ });+ }+testWidgets('pairing', (tester) async {await _shoot(tester, 'pairing', state: _demo(), section: Section.devices, arrange: () async {showDialog<void>(