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: add clipboard sharing and lifecycle controls
baiyuze764797c2060e
diff --git a/client-core/cmd/pasteferryd/main.go b/client-core/cmd/pasteferryd/main.goindex afc6e9a..dd30b89 100644--- a/client-core/cmd/pasteferryd/main.go+++ b/client-core/cmd/pasteferryd/main.go@@ -15,6 +15,7 @@ import ("os/signal""path/filepath""runtime"+ "slices""sync""syscall""time"@@ -457,6 +458,9 @@ func run(dataDir string) error {if err := saveCfg(c); err != nil {return err}+ if c.RealtimeSyncDisabled != prev.RealtimeSyncDisabled || c.SyncBacklog != prev.SyncBacklog || !slices.Equal(c.SyncDisabledPeers, prev.SyncDisabledPeers) {+ engine.ApplySyncPolicy()+ }if c.EffectiveSignalingURL() != prev.EffectiveSignalingURL() || c.ServiceMode != prev.ServiceMode {slog.Info("公网连接模式已变更")peerMgr.SetSignalingURL(c.EffectiveSignalingURL())diff --git a/client-core/cmd/pasteferryd/tray_windows.go b/client-core/cmd/pasteferryd/tray_windows.goindex 83721a8..6e1a6c1 100644--- a/client-core/cmd/pasteferryd/tray_windows.go+++ b/client-core/cmd/pasteferryd/tray_windows.go@@ -241,7 +241,8 @@ func (t *windowsTray) showMenu() {class, _ := windows.UTF16PtrFromString("FLUTTER_RUNNER_WIN32_WINDOW")title, _ := windows.UTF16PtrFromString("PasteFerry")if hwnd, _, _ := trayFindWindow.Call(uintptr(unsafe.Pointer(class)), uintptr(unsafe.Pointer(title))); hwnd != 0 {- trayPostMessage.Call(hwnd, trayWMClose, 0, 0)+ trayPostMessage.Call(hwnd, 0x8000+87, 0, 0)+ return // The UI confirms active transfers and stops all helpers.}t.quit() // 正常退出码 0:守护进程也退出,不会误当成崩溃再拉起}diff --git a/client-core/internal/config/config.go b/client-core/internal/config/config.goindex aec7253..f2d85ce 100644--- a/client-core/internal/config/config.go+++ b/client-core/internal/config/config.go@@ -33,6 +33,11 @@ type Config struct {HistoryTTL Duration `json:"history_ttl"` // 历史记录元数据保留期CacheTTL Duration `json:"cache_ttl"` // 已落盘内容的保留期+ // Sync controls affect automatic clipboard sharing, not local history or Send Files.+ RealtimeSyncDisabled bool `json:"realtime_sync_disabled,omitempty"`+ SyncBacklog bool `json:"sync_backlog,omitempty"`+ SyncDisabledPeers []string `json:"sync_disabled_peers,omitempty"`+SyncText bool `json:"sync_text"`SyncHTML bool `json:"sync_html"`SyncImage bool `json:"sync_image"`@@ -184,7 +189,7 @@ type Paths struct {// 收藏另存的图片与文件。不能放在 Cache 里面:GC 会把缓存目录里不认识的文件夹当成孤儿删掉Favorites stringConfig string- DB string+ DB string// daemon 启动后把 gRPC 端口和一次性 token 写在这里,供 UI 发现Endpoint string}@@ -229,8 +234,8 @@ func pathsUnder(root string) Paths {Cache: filepath.Join(root, "cache"),Favorites: filepath.Join(root, "favorites"),Config: filepath.Join(root, "config.json"),- DB: filepath.Join(root, "pasteferry.db"),- Endpoint: filepath.Join(root, "daemon.json"),+ DB: filepath.Join(root, "pasteferry.db"),+ Endpoint: filepath.Join(root, "daemon.json"),}}@@ -389,3 +394,16 @@ func (d *Duration) UnmarshalJSON(b []byte) error {}func (d Duration) Std() time.Duration { return time.Duration(d) }++// SyncAllowed reports whether automatic clipboard sharing with peer is enabled.+func (c Config) SyncAllowed(peer string) bool {+ if c.RealtimeSyncDisabled {+ return false+ }+ for _, id := range c.SyncDisabledPeers {+ if id == peer {+ return false+ }+ }+ return true+}diff --git a/client-core/internal/rpc/convert.go b/client-core/internal/rpc/convert.goindex 6515128..9e03484 100644--- a/client-core/internal/rpc/convert.go+++ b/client-core/internal/rpc/convert.go@@ -89,6 +89,9 @@ func configToProto(c config.Config) *pb.Config {ReceiveDisabled: c.ReceiveDisabled,ReceiveNotifyDisabled: c.ReceiveNotifyDisabled,SendLayoutStacked: c.SendLayoutStacked,+ RealtimeSyncDisabled: c.RealtimeSyncDisabled,+ SyncBacklog: c.SyncBacklog,+ SyncDisabledPeers: append([]string(nil), c.SyncDisabledPeers...),}}@@ -118,6 +121,9 @@ func configFromProto(in *pb.Config, base config.Config) config.Config {c.SyncFile = in.GetSyncFile()c.AutoApplyToClipboard = in.GetAutoApplyToClipboard()c.LaunchAtLogin = in.GetLaunchAtLogin()+ c.RealtimeSyncDisabled = in.GetRealtimeSyncDisabled()+ c.SyncBacklog = in.GetSyncBacklog()+ c.SyncDisabledPeers = append([]string(nil), in.GetSyncDisabledPeers()...)c.OnlyOwnSTUN = in.GetOnlyOwnStun()// 空字符串就是「跟随系统」,与「没设置」同义,直接覆盖c.Language = in.GetLanguage()diff --git a/client-core/internal/rpc/convert_update_test.go b/client-core/internal/rpc/convert_update_test.goindex c05c6f0..b85d0ba 100644--- a/client-core/internal/rpc/convert_update_test.go+++ b/client-core/internal/rpc/convert_update_test.go@@ -23,3 +23,19 @@ func TestUpdateSettingsRoundTrip(t *testing.T) {t.Fatalf("update settings not cleared: %+v", got)}}++func TestSyncPolicyRoundTrip(t *testing.T) {+ c := config.Default()+ c.RealtimeSyncDisabled = true+ c.SyncBacklog = true+ c.SyncDisabledPeers = []string{"home", "office"}+ got := configFromProto(configToProto(c), config.Default())+ if !got.RealtimeSyncDisabled || !got.SyncBacklog || len(got.SyncDisabledPeers) != 2 || got.SyncDisabledPeers[0] != "home" {+ t.Fatalf("lost policy: %+v", got)+ }+ in := configToProto(config.Default())+ got = configFromProto(in, c)+ if got.RealtimeSyncDisabled || got.SyncBacklog || len(got.SyncDisabledPeers) != 0 {+ t.Fatalf("failed to clear policy: %+v", got)+ }+}diff --git a/client-core/internal/sync/backlog.go b/client-core/internal/sync/backlog.goindex c4d1515..f1d5798 100644--- a/client-core/internal/sync/backlog.go+++ b/client-core/internal/sync/backlog.go@@ -2,6 +2,7 @@ package syncimport ("context"+ "errors""slices""sync""time"@@ -26,6 +27,10 @@ type backlog struct {func (b *backlog) add(peer, clipID string) {b.mu.Lock()defer b.mu.Unlock()+ b.addLocked(peer, clipID)+}++func (b *backlog) addLocked(peer, clipID string) {if b.pending == nil {b.pending = make(map[string][]string)}@@ -57,8 +62,11 @@ func (e *Engine) offerToPeers(ctx context.Context, clip store.Clip, cfg config.Cmsg := &pb.PeerMessage{Payload: &pb.PeerMessage_Offer{Offer: offer}}var reached []stringfor _, peer := range peers {+ if !cfg.SyncAllowed(peer) || !e.loadConfig().SyncAllowed(peer) {+ continue+ }if err := e.send(peer, msg); err != nil {- e.backlog.add(peer, clip.ID)+ e.queueMissed(peer, clip.ID)continue}reached = append(reached, peer)@@ -79,13 +87,21 @@ func (e *Engine) offerToPeers(ctx context.Context, clip store.Clip, cfg config.C// 补发的 offer 带 backlog 标记,对端只记进复制记录、不写进剪贴板:// 它此刻剪贴板里的内容比这些旧内容更新。func (e *Engine) PeerReady(ctx context.Context, peer string) {+ generation := e.policyGeneration.Load()ids := e.backlog.take(peer)if len(ids) == 0 {return}cfg := e.loadConfig()+ if !cfg.SyncBacklog || !cfg.SyncAllowed(peer) {+ return+ }var sent intfor i, id := range ids {+ cfg = e.loadConfig()+ if generation != e.policyGeneration.Load() || !cfg.SyncBacklog || !cfg.SyncAllowed(peer) {+ break+ }clip, err := e.store.GetClip(id)if err != nil || time.Since(clip.CreatedAt) > backlogMaxAge {continue // 已删除或太旧@@ -95,7 +111,7 @@ func (e *Engine) PeerReady(ctx context.Context, peer string) {if err := e.send(peer, &pb.PeerMessage{Payload: &pb.PeerMessage_Offer{Offer: offer}}); err != nil {// 刚连上又断了:剩下的放回去,等下次for _, rest := range ids[i:] {- e.backlog.add(peer, rest)+ e.queueMissed(peer, rest)}break}@@ -113,12 +129,56 @@ func (e *Engine) PeerReady(ctx context.Context, peer string) {// pushOrRequeue 推送内容;中途断了就记进待补发,重连后连同 offer 一起重来,// 不让对端的记录一直停在「接收中」。func (e *Engine) pushOrRequeue(ctx context.Context, peer string, clip store.Clip) {+ generation := e.policyGeneration.Load()+ if !e.loadConfig().SyncAllowed(peer) {+ return+ }if err := e.pushTo(ctx, peer, clip); err != nil {e.log.Warn("推送内容失败,连接恢复后补发", "clip", clip.ID, "to", peer, "err", err)- e.backlog.add(peer, clip.ID)+ if generation == e.policyGeneration.Load() {+ e.queueMissed(peer, clip.ID)+ }}}func pushes(offer *pb.ClipOffer, clip store.Clip) bool {return offer.GetWillPush() && (clip.Kind == store.KindFile || clip.Kind == store.KindImage)}++func (e *Engine) queueMissed(peer, id string) {+ e.backlog.mu.Lock()+ defer e.backlog.mu.Unlock()+ cfg := e.loadConfig()+ if cfg.SyncBacklog && cfg.SyncAllowed(peer) {+ e.backlog.addLocked(peer, id)+ }+}++// ApplySyncPolicy drops pending records immediately when sharing is paused.+// Resuming sharing therefore starts with new copies only.+func (e *Engine) ApplySyncPolicy() {+ e.policyGeneration.Add(1)+ e.offerMu.Lock()+ defer e.offerMu.Unlock()+ cfg := e.loadConfig()+ e.backlog.mu.Lock()+ for peer := range e.backlog.pending {+ if !cfg.SyncBacklog || !cfg.SyncAllowed(peer) {+ delete(e.backlog.pending, peer)+ }+ }+ e.backlog.mu.Unlock()+ e.mu.Lock()+ blocked := make(map[string]*receiveAttempt)+ for id, attempt := range e.receives {+ clip, err := e.store.GetClip(id)+ if err == nil && !attempt.manual && !attempt.preview &&+ (!cfg.SyncAllowed(clip.OriginDeviceID) || (e.quiet[id] && !cfg.SyncBacklog)) {+ blocked[id] = attempt+ }+ }+ e.mu.Unlock()+ for id, attempt := range blocked {+ e.failReceive(id, attempt, errors.New("clipboard sync paused"))+ }+}diff --git a/client-core/internal/sync/backlog_test.go b/client-core/internal/sync/backlog_test.goindex 0957393..7545e76 100644--- a/client-core/internal/sync/backlog_test.go+++ b/client-core/internal/sync/backlog_test.go@@ -67,6 +67,7 @@ func newBacklogEngine(t *testing.T, peers *fakePeers) *Engine {}t.Cleanup(func() { db.Close() })cfg := config.Default()+ cfg.SyncBacklog = truereturn &Engine{log: slog.New(slog.NewTextHandler(io.Discard, nil)),store: db,diff --git a/client-core/internal/sync/engine.go b/client-core/internal/sync/engine.goindex dd72f07..f450ec1 100644--- a/client-core/internal/sync/engine.go+++ b/client-core/internal/sync/engine.go@@ -23,6 +23,7 @@ import ("sort""strings""sync"+ "sync/atomic""time""github.com/pion/webrtc/v4"@@ -82,7 +83,8 @@ type Engine struct {quiet map[string]bool// 没送达对端、等连接恢复后补发的内容,见 backlog.go- backlog backlog+ backlog backlog+ policyGeneration atomic.Uint64// 上一次本机复制,用来认出同一次复制引起的重复变化,见 repeat.gorecentCopy repeatGuard@@ -103,8 +105,8 @@ type Options struct {Send func(deviceID string, msg *pb.PeerMessage) errorOpenStream func(deviceID, label string) (*webrtc.DataChannel, error)// PairedPeers 返回所有已配对设备,不论在线与否:连不上的记进待补发- PairedPeers func() []string- OnRecord func(*pb.ClipRecord)+ PairedPeers func() []string+ OnRecord func(*pb.ClipRecord)// OnRemoved 在引擎自己删掉一条记录时调用(取消收藏时合并掉的原记录等)OnRemoved func(clipID string)OnProgress func(*pb.TransferProgress)@@ -147,6 +149,7 @@ func New(opts Options) *Engine {// HandleClipboardChange 在本机剪贴板变化时调用。func (e *Engine) HandleClipboardChange(ctx context.Context, snap clipboard.Snapshot) {+ generation := e.policyGeneration.Load()cfg := e.loadConfig()if !e.kindEnabled(cfg, snap.Kind) {e.log.Debug("该类型已在设置中关闭,跳过", "kind", snap.Kind)@@ -186,6 +189,9 @@ func (e *Engine) HandleClipboardChange(ctx context.Context, snap clipboard.Snaps}e.emitRecord(clip)+ if generation != e.policyGeneration.Load() {+ return+ }e.offerToPeers(ctx, clip, cfg)}@@ -338,6 +344,10 @@ func (e *Engine) HandlePeerMessage(ctx context.Context, from string, msg *pb.Peefunc (e *Engine) handleOffer(ctx context.Context, from string, offer *pb.ClipOffer) {e.offerMu.Lock()defer e.offerMu.Unlock()+ policy := e.loadConfig()+ if !policy.SyncAllowed(from) || (offer.GetBacklog() && !policy.SyncBacklog) {+ return+ }if existing, err := e.store.GetClip(offer.GetClipId()); err == nil {// Offers are replayed after reconnect. Never erase a cache or an active// manual request, and never turn an old record into a new notification.@@ -722,7 +732,7 @@ func (e *Engine) finishReceive(r *receiver, cacheRel string, tops []string) boole.emitRecord(clip)e.completePendingFavorites(clip)result := &pb.ClipboardWriteResult{ClipId: clip.ID, Outcome: pb.ClipboardWriteOutcome_CLIPBOARD_WRITE_OUTCOME_PRESERVED}- if e.loadConfig().AutoApplyToClipboard && !quiet {+ if cfg := e.loadConfig(); cfg.AutoApplyToClipboard && !quiet && (a.manual || cfg.SyncAllowed(clip.OriginDeviceID)) {ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)defer cancel()if a.manual {diff --git a/client-core/internal/sync/policy_test.go b/client-core/internal/sync/policy_test.gonew file mode 100644index 0000000..64036a9--- /dev/null+++ b/client-core/internal/sync/policy_test.go@@ -0,0 +1,119 @@+package sync++import (+ "context"+ "testing"+ "time"++ "github.com/baiyuze/pasteferry/client-core/internal/config"+ pb "github.com/baiyuze/pasteferry/proto/gen/pasteferry/v1"+)++func TestDefaultPolicySkipsOfflineCopies(t *testing.T) {+ peers := &fakePeers{up: map[string]bool{"office": true}, offers: map[string][]*pb.ClipOffer{}}+ e := newBacklogEngine(t, peers)+ cfg := config.Default()+ e.loadConfig = func() config.Config { return cfg }+ ctx := context.Background()+ clip := putText(t, e, "missed", "offline", time.Now())+ e.offerToPeers(ctx, clip, cfg)+ peers.up["home"] = true+ e.PeerReady(ctx, "home")+ if len(peers.received("home")) != 0 {+ t.Fatal("default policy replayed offline copies")+ }+ clip = putText(t, e, "new", "online", time.Now())+ e.offerToPeers(ctx, clip, cfg)+ if got := peers.received("home"); len(got) != 1 || got[0].GetClipId() != "new" {+ t.Fatalf("new copy not delivered: %v", got)+ }+}++func TestPauseDropsQueueAndResumesWithNewCopies(t *testing.T) {+ for _, mode := range []string{"global", "peer", "backlog"} {+ t.Run(mode, func(t *testing.T) {+ peers := &fakePeers{up: map[string]bool{"office": true}, offers: map[string][]*pb.ClipOffer{}}+ e := newBacklogEngine(t, peers)+ cfg := config.Default()+ cfg.SyncBacklog = true+ e.loadConfig = func() config.Config { return cfg }+ ctx := context.Background()+ e.offerToPeers(ctx, putText(t, e, "before", "before", time.Now()), cfg)+ switch mode {+ case "global":+ cfg.RealtimeSyncDisabled = true+ case "peer":+ cfg.SyncDisabledPeers = []string{"home"}+ case "backlog":+ cfg.SyncBacklog = false+ }+ e.ApplySyncPolicy()+ e.offerToPeers(ctx, putText(t, e, "paused", "paused", time.Now()), cfg)+ cfg.RealtimeSyncDisabled = false+ cfg.SyncDisabledPeers = nil+ cfg.SyncBacklog = true+ peers.up["home"] = true+ e.PeerReady(ctx, "home")+ if len(peers.received("home")) != 0 {+ t.Fatal("resuming replayed old or paused copies")+ }+ e.offerToPeers(ctx, putText(t, e, "after", "after", time.Now()), cfg)+ got := peers.received("home")+ if len(got) != 1 || got[0].GetClipId() != "after" {+ t.Fatalf("unexpected delivery: %v", got)+ }+ })+ }+}++func TestIncomingPolicyRejectsPausedPeersAndDefaultBacklog(t *testing.T) {+ for _, mode := range []string{"global", "peer", "backlog"} {+ t.Run(mode, func(t *testing.T) {+ cfg := config.Default()+ switch mode {+ case "global":+ cfg.RealtimeSyncDisabled = true+ case "peer":+ cfg.SyncDisabledPeers = []string{"peer"}+ }+ e, events := receiveFixture(t, &receiveClipboard{}, cfg, 0)+ offerLarge(e, "ignored", mode == "backlog")+ if _, err := e.store.GetClip("ignored"); err == nil {+ t.Fatal("blocked offer appeared in history")+ }+ select {+ case event := <-events:+ t.Fatalf("blocked offer emitted event: %v", event)+ default:+ }+ })+ }+}++func TestPauseCancelsAutomaticReceivesButKeepsManualRequests(t *testing.T) {+ cfg := config.Default()+ e, _ := receiveFixture(t, &receiveClipboard{}, cfg, 0)+ e.loadConfig = func() config.Config { return cfg }+ offerLarge(e, "auto", false)+ offerLarge(e, "manual", false)+ for _, id := range []string{"auto", "manual"} {+ clip, err := e.store.GetClip(id)+ if err != nil {+ t.Fatal(err)+ }+ e.startAutomaticReceive(clip, false)+ }+ e.mu.Lock()+ e.receives["manual"].manual = true+ e.mu.Unlock()+ cfg.RealtimeSyncDisabled = true+ e.ApplySyncPolicy()+ e.mu.Lock()+ defer e.mu.Unlock()+ if e.receives["auto"] != nil {+ t.Fatal("automatic receive survived a pause")+ }+ if e.receives["manual"] == nil {+ t.Fatal("manual download was cancelled")+ }+}diff --git a/client-core/internal/sync/receive_test.go b/client-core/internal/sync/receive_test.goindex f94eb23..37a5d71 100644--- a/client-core/internal/sync/receive_test.go+++ b/client-core/internal/sync/receive_test.go@@ -93,7 +93,9 @@ func waitReceive(t *testing.T, events <-chan ReceiveEvent, stage ReceiveStage) R}func TestReceiveNotifiesOnlyNewLiveOffers(t *testing.T) {- e, events := receiveFixture(t, &receiveClipboard{}, config.Default(), 0)+ cfg := config.Default()+ cfg.SyncBacklog = true+ e, events := receiveFixture(t, &receiveClipboard{}, cfg, 0)offerLarge(e, "live", false)offerLarge(e, "live", false)offerLarge(e, "late", true)diff --git a/docs/assets/screenshots/devices.png b/docs/assets/screenshots/devices.pngindex 75e7706..8d17b7f 100644Binary files a/docs/assets/screenshots/devices.png and b/docs/assets/screenshots/devices.png differdiff --git a/docs/assets/screenshots/en/devices.png b/docs/assets/screenshots/en/devices.pngindex c0d78c1..432307c 100644Binary files a/docs/assets/screenshots/en/devices.png and b/docs/assets/screenshots/en/devices.png differdiff --git a/docs/assets/screenshots/en/favorites-dark.png b/docs/assets/screenshots/en/favorites-dark.pngindex 6f5bdae..d20aa8a 100644Binary files a/docs/assets/screenshots/en/favorites-dark.png and b/docs/assets/screenshots/en/favorites-dark.png differdiff --git a/docs/assets/screenshots/en/hover-dark.png b/docs/assets/screenshots/en/hover-dark.pngindex 50e3b28..9170d39 100644Binary files a/docs/assets/screenshots/en/hover-dark.png and b/docs/assets/screenshots/en/hover-dark.png differdiff --git a/docs/assets/screenshots/en/nearby-dark.png b/docs/assets/screenshots/en/nearby-dark.pngindex 963990c..8f5505d 100644Binary files a/docs/assets/screenshots/en/nearby-dark.png and b/docs/assets/screenshots/en/nearby-dark.png differdiff --git a/docs/assets/screenshots/en/nearby.png b/docs/assets/screenshots/en/nearby.pngindex 27ee226..4641422 100644Binary files a/docs/assets/screenshots/en/nearby.png and b/docs/assets/screenshots/en/nearby.png differdiff --git a/docs/assets/screenshots/en/official-settings-dark.png b/docs/assets/screenshots/en/official-settings-dark.pngindex 2ca1aa7..1e8c488 100644Binary files a/docs/assets/screenshots/en/official-settings-dark.png and b/docs/assets/screenshots/en/official-settings-dark.png differdiff --git a/docs/assets/screenshots/en/official-usage-dark.png b/docs/assets/screenshots/en/official-usage-dark.pngindex fe60767..c56b76b 100644Binary files a/docs/assets/screenshots/en/official-usage-dark.png and b/docs/assets/screenshots/en/official-usage-dark.png differdiff --git a/docs/assets/screenshots/en/pairing-dark.png b/docs/assets/screenshots/en/pairing-dark.pngindex f731183..f104f7f 100644Binary files a/docs/assets/screenshots/en/pairing-dark.png and b/docs/assets/screenshots/en/pairing-dark.png differdiff --git a/docs/assets/screenshots/en/pairing-join-dark.png b/docs/assets/screenshots/en/pairing-join-dark.pngindex 28dd0e3..65a45a9 100644Binary files a/docs/assets/screenshots/en/pairing-join-dark.png and b/docs/assets/screenshots/en/pairing-join-dark.png differdiff --git a/docs/assets/screenshots/en/pairing-join-ts-dark.png b/docs/assets/screenshots/en/pairing-join-ts-dark.pngindex 1f35a9d..f7b28b5 100644Binary files a/docs/assets/screenshots/en/pairing-join-ts-dark.png and b/docs/assets/screenshots/en/pairing-join-ts-dark.png differdiff --git a/docs/assets/screenshots/en/pairing.png b/docs/assets/screenshots/en/pairing.pngindex 22eaf91..8565273 100644Binary files a/docs/assets/screenshots/en/pairing.png and b/docs/assets/screenshots/en/pairing.png differdiff --git a/docs/assets/screenshots/en/send-dark.png b/docs/assets/screenshots/en/send-dark.pngindex ed4c7ef..58619e3 100644Binary files a/docs/assets/screenshots/en/send-dark.png and b/docs/assets/screenshots/en/send-dark.png differdiff --git a/docs/assets/screenshots/en/send-dialog-dark.png b/docs/assets/screenshots/en/send-dialog-dark.pngindex 50ac95d..6e88613 100644Binary files a/docs/assets/screenshots/en/send-dialog-dark.png and b/docs/assets/screenshots/en/send-dialog-dark.png differdiff --git a/docs/assets/screenshots/en/send-small-short.png b/docs/assets/screenshots/en/send-small-short.pngnew file mode 100644index 0000000..a864ce3Binary files /dev/null and b/docs/assets/screenshots/en/send-small-short.png differdiff --git a/docs/assets/screenshots/en/send-small-tall.png b/docs/assets/screenshots/en/send-small-tall.pngnew file mode 100644index 0000000..a5f14f5Binary files /dev/null and b/docs/assets/screenshots/en/send-small-tall.png differdiff --git a/docs/assets/screenshots/en/send.png b/docs/assets/screenshots/en/send.pngindex 4387f4b..366ca8b 100644Binary files a/docs/assets/screenshots/en/send.png and b/docs/assets/screenshots/en/send.png differdiff --git a/docs/assets/screenshots/en/settings-cloud-dark.png b/docs/assets/screenshots/en/settings-cloud-dark.pngindex f49fbdd..ab8b197 100644Binary files a/docs/assets/screenshots/en/settings-cloud-dark.png and b/docs/assets/screenshots/en/settings-cloud-dark.png differdiff --git a/docs/assets/screenshots/en/settings-lan-dark.png b/docs/assets/screenshots/en/settings-lan-dark.pngindex 246e0f0..04f2d87 100644Binary files a/docs/assets/screenshots/en/settings-lan-dark.png and b/docs/assets/screenshots/en/settings-lan-dark.png differdiff --git a/docs/assets/screenshots/en/settings.png b/docs/assets/screenshots/en/settings.pngindex 421183d..41744c5 100644Binary files a/docs/assets/screenshots/en/settings.png and b/docs/assets/screenshots/en/settings.png differdiff --git a/docs/assets/screenshots/en/verify.png b/docs/assets/screenshots/en/verify.pngindex c0b8b18..27f08a0 100644Binary files a/docs/assets/screenshots/en/verify.png and b/docs/assets/screenshots/en/verify.png differdiff --git a/docs/assets/screenshots/en/welcome-dark.png b/docs/assets/screenshots/en/welcome-dark.pngindex 11d5224..9421501 100644Binary files a/docs/assets/screenshots/en/welcome-dark.png and b/docs/assets/screenshots/en/welcome-dark.png differdiff --git a/docs/assets/screenshots/en/welcome.png b/docs/assets/screenshots/en/welcome.pngindex 6903a72..04f747e 100644Binary files a/docs/assets/screenshots/en/welcome.png and b/docs/assets/screenshots/en/welcome.png differdiff --git a/docs/assets/screenshots/favorites-dark.png b/docs/assets/screenshots/favorites-dark.pngindex dcce5c3..22450be 100644Binary files a/docs/assets/screenshots/favorites-dark.png and b/docs/assets/screenshots/favorites-dark.png differdiff --git a/docs/assets/screenshots/hover-dark.png b/docs/assets/screenshots/hover-dark.pngindex e5e811e..db26eba 100644Binary files a/docs/assets/screenshots/hover-dark.png and b/docs/assets/screenshots/hover-dark.png differdiff --git a/docs/assets/screenshots/ja/card-picker-dark.png b/docs/assets/screenshots/ja/card-picker-dark.pngindex 471e486..9ab9eb8 100644Binary files a/docs/assets/screenshots/ja/card-picker-dark.png and b/docs/assets/screenshots/ja/card-picker-dark.png differdiff --git a/docs/assets/screenshots/ja/devices.png b/docs/assets/screenshots/ja/devices.pngindex 7d29d43..fc6238d 100644Binary files a/docs/assets/screenshots/ja/devices.png and b/docs/assets/screenshots/ja/devices.png differdiff --git a/docs/assets/screenshots/ja/favorites-dark.png b/docs/assets/screenshots/ja/favorites-dark.pngindex e12d2b9..8101bdd 100644Binary files a/docs/assets/screenshots/ja/favorites-dark.png and b/docs/assets/screenshots/ja/favorites-dark.png differdiff --git a/docs/assets/screenshots/ja/hover-dark.png b/docs/assets/screenshots/ja/hover-dark.pngindex 42c73f7..21c5854 100644Binary files a/docs/assets/screenshots/ja/hover-dark.png and b/docs/assets/screenshots/ja/hover-dark.png differdiff --git a/docs/assets/screenshots/ja/nearby-dark.png b/docs/assets/screenshots/ja/nearby-dark.pngindex c46a1bd..d3fc042 100644Binary files a/docs/assets/screenshots/ja/nearby-dark.png and b/docs/assets/screenshots/ja/nearby-dark.png differdiff --git a/docs/assets/screenshots/ja/nearby.png b/docs/assets/screenshots/ja/nearby.pngindex 7c3088c..7464b19 100644Binary files a/docs/assets/screenshots/ja/nearby.png and b/docs/assets/screenshots/ja/nearby.png differdiff --git a/docs/assets/screenshots/ja/official-settings-dark.png b/docs/assets/screenshots/ja/official-settings-dark.pngindex 63e0c94..f153b10 100644Binary files a/docs/assets/screenshots/ja/official-settings-dark.png and b/docs/assets/screenshots/ja/official-settings-dark.png differdiff --git a/docs/assets/screenshots/ja/official-usage-dark.png b/docs/assets/screenshots/ja/official-usage-dark.pngindex 5082b45..062041b 100644Binary files a/docs/assets/screenshots/ja/official-usage-dark.png and b/docs/assets/screenshots/ja/official-usage-dark.png differdiff --git a/docs/assets/screenshots/ja/pairing-dark.png b/docs/assets/screenshots/ja/pairing-dark.pngindex 96a2e98..d690f92 100644Binary files a/docs/assets/screenshots/ja/pairing-dark.png and b/docs/assets/screenshots/ja/pairing-dark.png differdiff --git a/docs/assets/screenshots/ja/pairing-join-dark.png b/docs/assets/screenshots/ja/pairing-join-dark.pngindex 7fcc805..58cdec1 100644Binary files a/docs/assets/screenshots/ja/pairing-join-dark.png and b/docs/assets/screenshots/ja/pairing-join-dark.png differdiff --git a/docs/assets/screenshots/ja/pairing-join-ts-dark.png b/docs/assets/screenshots/ja/pairing-join-ts-dark.pngindex c5a8385..f322662 100644Binary files a/docs/assets/screenshots/ja/pairing-join-ts-dark.png and b/docs/assets/screenshots/ja/pairing-join-ts-dark.png differdiff --git a/docs/assets/screenshots/ja/pairing.png b/docs/assets/screenshots/ja/pairing.pngindex e992a64..e5ff4d1 100644Binary files a/docs/assets/screenshots/ja/pairing.png and b/docs/assets/screenshots/ja/pairing.png differdiff --git a/docs/assets/screenshots/ja/send-dark.png b/docs/assets/screenshots/ja/send-dark.pngindex c9923b7..f88904e 100644Binary files a/docs/assets/screenshots/ja/send-dark.png and b/docs/assets/screenshots/ja/send-dark.png differdiff --git a/docs/assets/screenshots/ja/send-dialog-dark.png b/docs/assets/screenshots/ja/send-dialog-dark.pngindex ababa02..e25db94 100644Binary files a/docs/assets/screenshots/ja/send-dialog-dark.png and b/docs/assets/screenshots/ja/send-dialog-dark.png differdiff --git a/docs/assets/screenshots/ja/send-small-short.png b/docs/assets/screenshots/ja/send-small-short.pngnew file mode 100644index 0000000..31ce05aBinary files /dev/null and b/docs/assets/screenshots/ja/send-small-short.png differdiff --git a/docs/assets/screenshots/ja/send-small-tall.png b/docs/assets/screenshots/ja/send-small-tall.pngnew file mode 100644index 0000000..a3879aeBinary files /dev/null and b/docs/assets/screenshots/ja/send-small-tall.png differdiff --git a/docs/assets/screenshots/ja/send.png b/docs/assets/screenshots/ja/send.pngindex f144174..0e1b08f 100644Binary files a/docs/assets/screenshots/ja/send.png and b/docs/assets/screenshots/ja/send.png differdiff --git a/docs/assets/screenshots/ja/settings-cloud-dark.png b/docs/assets/screenshots/ja/settings-cloud-dark.pngindex 4422014..df95f70 100644Binary files a/docs/assets/screenshots/ja/settings-cloud-dark.png and b/docs/assets/screenshots/ja/settings-cloud-dark.png differdiff --git a/docs/assets/screenshots/ja/settings-lan-dark.png b/docs/assets/screenshots/ja/settings-lan-dark.pngindex f7ab76c..37b3b27 100644Binary files a/docs/assets/screenshots/ja/settings-lan-dark.png and b/docs/assets/screenshots/ja/settings-lan-dark.png differdiff --git a/docs/assets/screenshots/ja/settings.png b/docs/assets/screenshots/ja/settings.pngindex 8a2551b..9ac7a8e 100644Binary files a/docs/assets/screenshots/ja/settings.png and b/docs/assets/screenshots/ja/settings.png differdiff --git a/docs/assets/screenshots/ja/verify.png b/docs/assets/screenshots/ja/verify.pngindex b9b47fe..ee4f181 100644Binary files a/docs/assets/screenshots/ja/verify.png and b/docs/assets/screenshots/ja/verify.png differdiff --git a/docs/assets/screenshots/ja/welcome-dark.png b/docs/assets/screenshots/ja/welcome-dark.pngindex 7d4c21f..b516645 100644Binary files a/docs/assets/screenshots/ja/welcome-dark.png and b/docs/assets/screenshots/ja/welcome-dark.png differdiff --git a/docs/assets/screenshots/ja/welcome.png b/docs/assets/screenshots/ja/welcome.pngindex 9be6dc0..521b7a4 100644Binary files a/docs/assets/screenshots/ja/welcome.png and b/docs/assets/screenshots/ja/welcome.png differdiff --git a/docs/assets/screenshots/nearby-dark.png b/docs/assets/screenshots/nearby-dark.pngindex a129934..d617728 100644Binary files a/docs/assets/screenshots/nearby-dark.png and b/docs/assets/screenshots/nearby-dark.png differdiff --git a/docs/assets/screenshots/nearby.png b/docs/assets/screenshots/nearby.pngindex f02abb4..79319ac 100644Binary files a/docs/assets/screenshots/nearby.png and b/docs/assets/screenshots/nearby.png differdiff --git a/docs/assets/screenshots/official-settings-dark.png b/docs/assets/screenshots/official-settings-dark.pngindex cb36c3e..9da7c00 100644Binary files a/docs/assets/screenshots/official-settings-dark.png and b/docs/assets/screenshots/official-settings-dark.png differdiff --git a/docs/assets/screenshots/official-usage-dark.png b/docs/assets/screenshots/official-usage-dark.pngindex 2ca51b7..4157c41 100644Binary files a/docs/assets/screenshots/official-usage-dark.png and b/docs/assets/screenshots/official-usage-dark.png differdiff --git a/docs/assets/screenshots/pairing-dark.png b/docs/assets/screenshots/pairing-dark.pngindex e0e2730..56f992f 100644Binary files a/docs/assets/screenshots/pairing-dark.png and b/docs/assets/screenshots/pairing-dark.png differdiff --git a/docs/assets/screenshots/pairing-join-dark.png b/docs/assets/screenshots/pairing-join-dark.pngindex 32de5a8..f0adccf 100644Binary files a/docs/assets/screenshots/pairing-join-dark.png and b/docs/assets/screenshots/pairing-join-dark.png differdiff --git a/docs/assets/screenshots/pairing-join-ts-dark.png b/docs/assets/screenshots/pairing-join-ts-dark.pngindex 0d2c19e..9a8a132 100644Binary files a/docs/assets/screenshots/pairing-join-ts-dark.png and b/docs/assets/screenshots/pairing-join-ts-dark.png differdiff --git a/docs/assets/screenshots/pairing.png b/docs/assets/screenshots/pairing.pngindex 064188f..3628268 100644Binary files a/docs/assets/screenshots/pairing.png and b/docs/assets/screenshots/pairing.png differdiff --git a/docs/assets/screenshots/send-dark.png b/docs/assets/screenshots/send-dark.pngindex 54f27d2..0f10003 100644Binary files a/docs/assets/screenshots/send-dark.png and b/docs/assets/screenshots/send-dark.png differdiff --git a/docs/assets/screenshots/send-dialog-dark.png b/docs/assets/screenshots/send-dialog-dark.pngindex de4ef35..46e46b3 100644Binary files a/docs/assets/screenshots/send-dialog-dark.png and b/docs/assets/screenshots/send-dialog-dark.png differdiff --git a/docs/assets/screenshots/send-small-short.png b/docs/assets/screenshots/send-small-short.pngnew file mode 100644index 0000000..b2111ccBinary files /dev/null and b/docs/assets/screenshots/send-small-short.png differdiff --git a/docs/assets/screenshots/send-small-tall.png b/docs/assets/screenshots/send-small-tall.pngnew file mode 100644index 0000000..f02541eBinary files /dev/null and b/docs/assets/screenshots/send-small-tall.png differdiff --git a/docs/assets/screenshots/send.png b/docs/assets/screenshots/send.pngindex 6663299..e13c178 100644Binary files a/docs/assets/screenshots/send.png and b/docs/assets/screenshots/send.png differdiff --git a/docs/assets/screenshots/settings-cloud-dark.png b/docs/assets/screenshots/settings-cloud-dark.pngindex 5409241..133c85b 100644Binary files a/docs/assets/screenshots/settings-cloud-dark.png and b/docs/assets/screenshots/settings-cloud-dark.png differdiff --git a/docs/assets/screenshots/settings-lan-dark.png b/docs/assets/screenshots/settings-lan-dark.pngindex b065b57..2f2df12 100644Binary files a/docs/assets/screenshots/settings-lan-dark.png and b/docs/assets/screenshots/settings-lan-dark.png differdiff --git a/docs/assets/screenshots/settings.png b/docs/assets/screenshots/settings.pngindex aecfb7d..fcc3e46 100644Binary files a/docs/assets/screenshots/settings.png and b/docs/assets/screenshots/settings.png differdiff --git a/docs/assets/screenshots/verify.png b/docs/assets/screenshots/verify.pngindex e3ff788..4e380cd 100644Binary files a/docs/assets/screenshots/verify.png and b/docs/assets/screenshots/verify.png differdiff --git a/docs/assets/screenshots/welcome-dark.png b/docs/assets/screenshots/welcome-dark.pngindex e38fc81..073d04d 100644Binary files a/docs/assets/screenshots/welcome-dark.png and b/docs/assets/screenshots/welcome-dark.png differdiff --git a/docs/assets/screenshots/welcome.png b/docs/assets/screenshots/welcome.pngindex b9eff42..783ebb8 100644Binary files a/docs/assets/screenshots/welcome.png and b/docs/assets/screenshots/welcome.png differdiff --git a/docs/assets/screenshots/zh-hk/card-picker-dark.png b/docs/assets/screenshots/zh-hk/card-picker-dark.pngindex e5de016..9359b27 100644Binary files a/docs/assets/screenshots/zh-hk/card-picker-dark.png and b/docs/assets/screenshots/zh-hk/card-picker-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/devices.png b/docs/assets/screenshots/zh-hk/devices.pngindex a954559..ba9193b 100644Binary files a/docs/assets/screenshots/zh-hk/devices.png and b/docs/assets/screenshots/zh-hk/devices.png differdiff --git a/docs/assets/screenshots/zh-hk/favorites-dark.png b/docs/assets/screenshots/zh-hk/favorites-dark.pngindex 5ef00ea..9daf6e8 100644Binary files a/docs/assets/screenshots/zh-hk/favorites-dark.png and b/docs/assets/screenshots/zh-hk/favorites-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/hover-dark.png b/docs/assets/screenshots/zh-hk/hover-dark.pngindex ddbdde4..80d8ccf 100644Binary files a/docs/assets/screenshots/zh-hk/hover-dark.png and b/docs/assets/screenshots/zh-hk/hover-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/nearby-dark.png b/docs/assets/screenshots/zh-hk/nearby-dark.pngindex 3ef4683..c188e54 100644Binary files a/docs/assets/screenshots/zh-hk/nearby-dark.png and b/docs/assets/screenshots/zh-hk/nearby-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/nearby.png b/docs/assets/screenshots/zh-hk/nearby.pngindex a7d6023..934ec63 100644Binary files a/docs/assets/screenshots/zh-hk/nearby.png and b/docs/assets/screenshots/zh-hk/nearby.png differdiff --git a/docs/assets/screenshots/zh-hk/official-settings-dark.png b/docs/assets/screenshots/zh-hk/official-settings-dark.pngindex 75cae25..839c1a9 100644Binary files a/docs/assets/screenshots/zh-hk/official-settings-dark.png and b/docs/assets/screenshots/zh-hk/official-settings-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/official-usage-dark.png b/docs/assets/screenshots/zh-hk/official-usage-dark.pngindex 74e0377..2a8d9f7 100644Binary files a/docs/assets/screenshots/zh-hk/official-usage-dark.png and b/docs/assets/screenshots/zh-hk/official-usage-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/pairing-dark.png b/docs/assets/screenshots/zh-hk/pairing-dark.pngindex 770943a..e0beaf2 100644Binary files a/docs/assets/screenshots/zh-hk/pairing-dark.png and b/docs/assets/screenshots/zh-hk/pairing-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/pairing-join-dark.png b/docs/assets/screenshots/zh-hk/pairing-join-dark.pngindex 4331cae..4729e4d 100644Binary files a/docs/assets/screenshots/zh-hk/pairing-join-dark.png and b/docs/assets/screenshots/zh-hk/pairing-join-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/pairing-join-ts-dark.png b/docs/assets/screenshots/zh-hk/pairing-join-ts-dark.pngindex 10df711..d505274 100644Binary files a/docs/assets/screenshots/zh-hk/pairing-join-ts-dark.png and b/docs/assets/screenshots/zh-hk/pairing-join-ts-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/pairing.png b/docs/assets/screenshots/zh-hk/pairing.pngindex 563a39a..798e1ef 100644Binary files a/docs/assets/screenshots/zh-hk/pairing.png and b/docs/assets/screenshots/zh-hk/pairing.png differdiff --git a/docs/assets/screenshots/zh-hk/send-dark.png b/docs/assets/screenshots/zh-hk/send-dark.pngindex 959da47..4be17bf 100644Binary files a/docs/assets/screenshots/zh-hk/send-dark.png and b/docs/assets/screenshots/zh-hk/send-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/send-dialog-dark.png b/docs/assets/screenshots/zh-hk/send-dialog-dark.pngindex 09ff49e..dad055c 100644Binary files a/docs/assets/screenshots/zh-hk/send-dialog-dark.png and b/docs/assets/screenshots/zh-hk/send-dialog-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/send-small-short.png b/docs/assets/screenshots/zh-hk/send-small-short.pngnew file mode 100644index 0000000..4dfda89Binary files /dev/null and b/docs/assets/screenshots/zh-hk/send-small-short.png differdiff --git a/docs/assets/screenshots/zh-hk/send-small-tall.png b/docs/assets/screenshots/zh-hk/send-small-tall.pngnew file mode 100644index 0000000..1fe178aBinary files /dev/null and b/docs/assets/screenshots/zh-hk/send-small-tall.png differdiff --git a/docs/assets/screenshots/zh-hk/send.png b/docs/assets/screenshots/zh-hk/send.pngindex 26aeb1f..fd4ca5b 100644Binary files a/docs/assets/screenshots/zh-hk/send.png and b/docs/assets/screenshots/zh-hk/send.png differdiff --git a/docs/assets/screenshots/zh-hk/settings-cloud-dark.png b/docs/assets/screenshots/zh-hk/settings-cloud-dark.pngindex 6053d7f..6d6c77c 100644Binary files a/docs/assets/screenshots/zh-hk/settings-cloud-dark.png and b/docs/assets/screenshots/zh-hk/settings-cloud-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/settings-lan-dark.png b/docs/assets/screenshots/zh-hk/settings-lan-dark.pngindex 26953d9..c156bcf 100644Binary files a/docs/assets/screenshots/zh-hk/settings-lan-dark.png and b/docs/assets/screenshots/zh-hk/settings-lan-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/settings.png b/docs/assets/screenshots/zh-hk/settings.pngindex 61668cc..fb0397c 100644Binary files a/docs/assets/screenshots/zh-hk/settings.png and b/docs/assets/screenshots/zh-hk/settings.png differdiff --git a/docs/assets/screenshots/zh-hk/verify.png b/docs/assets/screenshots/zh-hk/verify.pngindex 39b051d..769f246 100644Binary files a/docs/assets/screenshots/zh-hk/verify.png and b/docs/assets/screenshots/zh-hk/verify.png differdiff --git a/docs/assets/screenshots/zh-hk/welcome-dark.png b/docs/assets/screenshots/zh-hk/welcome-dark.pngindex f358e0a..4e63328 100644Binary files a/docs/assets/screenshots/zh-hk/welcome-dark.png and b/docs/assets/screenshots/zh-hk/welcome-dark.png differdiff --git a/docs/assets/screenshots/zh-hk/welcome.png b/docs/assets/screenshots/zh-hk/welcome.pngindex a050035..343015a 100644Binary files a/docs/assets/screenshots/zh-hk/welcome.png and b/docs/assets/screenshots/zh-hk/welcome.png differdiff --git a/docs/assets/screenshots/zh-tw/devices.png b/docs/assets/screenshots/zh-tw/devices.pngindex b03f36e..7a709c6 100644Binary files a/docs/assets/screenshots/zh-tw/devices.png and b/docs/assets/screenshots/zh-tw/devices.png differdiff --git a/docs/assets/screenshots/zh-tw/favorites-dark.png b/docs/assets/screenshots/zh-tw/favorites-dark.pngindex 7320b7a..f6bfdb8 100644Binary files a/docs/assets/screenshots/zh-tw/favorites-dark.png and b/docs/assets/screenshots/zh-tw/favorites-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/hover-dark.png b/docs/assets/screenshots/zh-tw/hover-dark.pngindex 57a18ef..404aebf 100644Binary files a/docs/assets/screenshots/zh-tw/hover-dark.png and b/docs/assets/screenshots/zh-tw/hover-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/nearby-dark.png b/docs/assets/screenshots/zh-tw/nearby-dark.pngindex 0958a94..20bc65b 100644Binary files a/docs/assets/screenshots/zh-tw/nearby-dark.png and b/docs/assets/screenshots/zh-tw/nearby-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/nearby.png b/docs/assets/screenshots/zh-tw/nearby.pngindex 6926154..d2a3be5 100644Binary files a/docs/assets/screenshots/zh-tw/nearby.png and b/docs/assets/screenshots/zh-tw/nearby.png differdiff --git a/docs/assets/screenshots/zh-tw/official-settings-dark.png b/docs/assets/screenshots/zh-tw/official-settings-dark.pngindex 066f15a..c5dff94 100644Binary files a/docs/assets/screenshots/zh-tw/official-settings-dark.png and b/docs/assets/screenshots/zh-tw/official-settings-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/official-usage-dark.png b/docs/assets/screenshots/zh-tw/official-usage-dark.pngindex d3e4d8c..c0933db 100644Binary files a/docs/assets/screenshots/zh-tw/official-usage-dark.png and b/docs/assets/screenshots/zh-tw/official-usage-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/pairing-dark.png b/docs/assets/screenshots/zh-tw/pairing-dark.pngindex 5a4843d..20d7e86 100644Binary files a/docs/assets/screenshots/zh-tw/pairing-dark.png and b/docs/assets/screenshots/zh-tw/pairing-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/pairing-join-dark.png b/docs/assets/screenshots/zh-tw/pairing-join-dark.pngindex 435f5b8..5c4d40a 100644Binary files a/docs/assets/screenshots/zh-tw/pairing-join-dark.png and b/docs/assets/screenshots/zh-tw/pairing-join-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/pairing-join-ts-dark.png b/docs/assets/screenshots/zh-tw/pairing-join-ts-dark.pngindex adfaae9..219ac36 100644Binary files a/docs/assets/screenshots/zh-tw/pairing-join-ts-dark.png and b/docs/assets/screenshots/zh-tw/pairing-join-ts-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/pairing.png b/docs/assets/screenshots/zh-tw/pairing.pngindex 71cd531..2305a59 100644Binary files a/docs/assets/screenshots/zh-tw/pairing.png and b/docs/assets/screenshots/zh-tw/pairing.png differdiff --git a/docs/assets/screenshots/zh-tw/send-dark.png b/docs/assets/screenshots/zh-tw/send-dark.pngindex d07fe1e..e89243b 100644Binary files a/docs/assets/screenshots/zh-tw/send-dark.png and b/docs/assets/screenshots/zh-tw/send-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/send-dialog-dark.png b/docs/assets/screenshots/zh-tw/send-dialog-dark.pngindex 0bdc859..20f4b9e 100644Binary files a/docs/assets/screenshots/zh-tw/send-dialog-dark.png and b/docs/assets/screenshots/zh-tw/send-dialog-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/send-small-short.png b/docs/assets/screenshots/zh-tw/send-small-short.pngnew file mode 100644index 0000000..24fa867Binary files /dev/null and b/docs/assets/screenshots/zh-tw/send-small-short.png differdiff --git a/docs/assets/screenshots/zh-tw/send-small-tall.png b/docs/assets/screenshots/zh-tw/send-small-tall.pngnew file mode 100644index 0000000..ad36fa7Binary files /dev/null and b/docs/assets/screenshots/zh-tw/send-small-tall.png differdiff --git a/docs/assets/screenshots/zh-tw/send.png b/docs/assets/screenshots/zh-tw/send.pngindex 35832fa..7dd5c24 100644Binary files a/docs/assets/screenshots/zh-tw/send.png and b/docs/assets/screenshots/zh-tw/send.png differdiff --git a/docs/assets/screenshots/zh-tw/settings-cloud-dark.png b/docs/assets/screenshots/zh-tw/settings-cloud-dark.pngindex 0e497d5..9b6a119 100644Binary files a/docs/assets/screenshots/zh-tw/settings-cloud-dark.png and b/docs/assets/screenshots/zh-tw/settings-cloud-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/settings-lan-dark.png b/docs/assets/screenshots/zh-tw/settings-lan-dark.pngindex ffa401e..2bd2fce 100644Binary files a/docs/assets/screenshots/zh-tw/settings-lan-dark.png and b/docs/assets/screenshots/zh-tw/settings-lan-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/settings.png b/docs/assets/screenshots/zh-tw/settings.pngindex d840650..f2109a7 100644Binary files a/docs/assets/screenshots/zh-tw/settings.png and b/docs/assets/screenshots/zh-tw/settings.png differdiff --git a/docs/assets/screenshots/zh-tw/verify.png b/docs/assets/screenshots/zh-tw/verify.pngindex 2078c91..b0cf47d 100644Binary files a/docs/assets/screenshots/zh-tw/verify.png and b/docs/assets/screenshots/zh-tw/verify.png differdiff --git a/docs/assets/screenshots/zh-tw/welcome-dark.png b/docs/assets/screenshots/zh-tw/welcome-dark.pngindex ee1c94a..b52a012 100644Binary files a/docs/assets/screenshots/zh-tw/welcome-dark.png and b/docs/assets/screenshots/zh-tw/welcome-dark.png differdiff --git a/docs/assets/screenshots/zh-tw/welcome.png b/docs/assets/screenshots/zh-tw/welcome.pngindex 9b3480e..515e811 100644Binary files a/docs/assets/screenshots/zh-tw/welcome.png and b/docs/assets/screenshots/zh-tw/welcome.png differdiff --git a/proto/gen/pasteferry/v1/daemon.pb.go b/proto/gen/pasteferry/v1/daemon.pb.goindex c44cf1e..f887d34 100644--- a/proto/gen/pasteferry/v1/daemon.pb.go+++ b/proto/gen/pasteferry/v1/daemon.pb.go@@ -2693,9 +2693,12 @@ type Config struct {// 收到文件时不发系统通知ReceiveNotifyDisabled bool `protobuf:"varint,25,opt,name=receive_notify_disabled,json=receiveNotifyDisabled,proto3" json:"receive_notify_disabled,omitempty"`// 隔空传送页里,传输列表放在雷达下面(上下排)。默认 false:放在雷达右边(左右排)- SendLayoutStacked bool `protobuf:"varint,26,opt,name=send_layout_stacked,json=sendLayoutStacked,proto3" json:"send_layout_stacked,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ SendLayoutStacked bool `protobuf:"varint,26,opt,name=send_layout_stacked,json=sendLayoutStacked,proto3" json:"send_layout_stacked,omitempty"`+ RealtimeSyncDisabled bool `protobuf:"varint,27,opt,name=realtime_sync_disabled,json=realtimeSyncDisabled,proto3" json:"realtime_sync_disabled,omitempty"`+ SyncBacklog bool `protobuf:"varint,28,opt,name=sync_backlog,json=syncBacklog,proto3" json:"sync_backlog,omitempty"`+ SyncDisabledPeers []string `protobuf:"bytes,29,rep,name=sync_disabled_peers,json=syncDisabledPeers,proto3" json:"sync_disabled_peers,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *Config) Reset() {@@ -2910,6 +2913,27 @@ func (x *Config) GetSendLayoutStacked() bool {return false}+func (x *Config) GetRealtimeSyncDisabled() bool {+ if x != nil {+ return x.RealtimeSyncDisabled+ }+ return false+}++func (x *Config) GetSyncBacklog() bool {+ if x != nil {+ return x.SyncBacklog+ }+ return false+}++func (x *Config) GetSyncDisabledPeers() []string {+ if x != nil {+ return x.SyncDisabledPeers+ }+ return nil+}+type OfficialUsage struct {state protoimpl.MessageState `protogen:"open.v1"`Available bool `protobuf:"varint,1,opt,name=available,proto3" json:"available,omitempty"`@@ -4987,7 +5011,7 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"\x04kind\x18\x01 \x01(\x0e2\x1d.pasteferry.v1.ConnectionKindR\x04kind\"P\n" +"\x17SetDeviceAddressRequest\x12\x1b\n" +"\tdevice_id\x18\x01 \x01(\tR\bdeviceId\x12\x18\n" +- "\aaddress\x18\x02 \x01(\tR\aaddress\"\xe9\b\n" ++ "\aaddress\x18\x02 \x01(\tR\aaddress\"\xf2\t\n" +"\x06Config\x129\n" +"\x19auto_sync_threshold_bytes\x18\x01 \x01(\x03R\x16autoSyncThresholdBytes\x12.\n" +"\x13history_ttl_seconds\x18\x02 \x01(\x03R\x11historyTtlSeconds\x12*\n" +@@ -5018,7 +5042,10 @@ const file_pasteferry_v1_daemon_proto_rawDesc = "" +"receiveDir\x12)\n" +"\x10receive_disabled\x18\x18 \x01(\bR\x0freceiveDisabled\x126\n" +"\x17receive_notify_disabled\x18\x19 \x01(\bR\x15receiveNotifyDisabled\x12.\n" +- "\x13send_layout_stacked\x18\x1a \x01(\bR\x11sendLayoutStacked\"\xd8\x02\n" ++ "\x13send_layout_stacked\x18\x1a \x01(\bR\x11sendLayoutStacked\x124\n" ++ "\x16realtime_sync_disabled\x18\x1b \x01(\bR\x14realtimeSyncDisabled\x12!\n" ++ "\fsync_backlog\x18\x1c \x01(\bR\vsyncBacklog\x12.\n" ++ "\x13sync_disabled_peers\x18\x1d \x03(\tR\x11syncDisabledPeers\"\xd8\x02\n" +"\rOfficialUsage\x12\x1c\n" +"\tavailable\x18\x01 \x01(\bR\tavailable\x12\x10\n" +"\x03day\x18\x02 \x01(\tR\x03day\x12\x1f\n" +diff --git a/proto/pasteferry/v1/daemon.proto b/proto/pasteferry/v1/daemon.protoindex 1861cae..7cb735e 100644--- a/proto/pasteferry/v1/daemon.proto+++ b/proto/pasteferry/v1/daemon.proto@@ -485,6 +485,9 @@ message Config {bool receive_notify_disabled = 25;// 隔空传送页里,传输列表放在雷达下面(上下排)。默认 false:放在雷达右边(左右排)bool send_layout_stacked = 26;+ bool realtime_sync_disabled = 27;+ bool sync_backlog = 28;+ repeated string sync_disabled_peers = 29;}enum ServiceMode {diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dartindex 65a50d6..02106f5 100644--- a/ui/lib/app_state.dart+++ b/ui/lib/app_state.dart@@ -19,7 +19,15 @@ enum LinkState { connecting, online, offline }typedef PairingCode = ({String code, List<String> addresses});/// 隔空传送发不出去的原因,后台服务把它写在错误消息里(见 rpc/send.go)。-enum SendFailure { offline, unsupported, disabled, needRelayConsent, noPaths, unknownDevice, other }+enum SendFailure {+ offline,+ unsupported,+ disabled,+ needRelayConsent,+ noPaths,+ unknownDevice,+ other,+}/// 配对失败的原因。后台服务把原因写在错误消息开头(见 rpc/server.go 的 pairingStatus)。enum PairingFailure {@@ -100,6 +108,10 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 连不上后台服务时,它的安装状态。界面据此决定显示欢迎页还是重启提示。ServiceState? _serviceState;bool _serviceChecked = false;+ bool _sessionStartTried = false;+ bool _quitting = false;+ Future<void>? _maintenance;+ Future<void>? _connectionWork;LinkState get link => _link;String? get error => _error;@@ -117,7 +129,8 @@ class AppState extends ChangeNotifier implements RecordDetails {_historySearch.resultsView?.where((r) => r.id == id).firstOrNull;/// 全部收藏的大小之和。硬链接、写时复制保存的副本实际占用更少,界面上写「最多」- int get favoritesBytes => _favorites.fold(0, (n, r) => n + r.totalSize.toInt());+ int get favoritesBytes =>+ _favorites.fold(0, (n, r) => n + r.totalSize.toInt());QuickPasteStatus? get quickPaste => _quickPaste;@@ -126,12 +139,18 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 收到了、还没在隔空传送页看过的批数(侧边栏的数字)int get unseenTransfers => _transfers- .where((t) => t.direction == TransferDirection.TRANSFER_DIRECTION_INCOMING && !t.seen && t.status == 'done')+ .where(+ (t) =>+ t.direction == TransferDirection.TRANSFER_DIRECTION_INCOMING &&+ !t.seen &&+ t.status == 'done',+ ).length;/// 正在收发的批次(统计、等待、传输中),侧边栏据此显示进度环- List<Transfer> get activeTransfers =>- _transfers.where((t) => const {'scanning', 'waiting', 'active'}.contains(t.status)).toList();+ List<Transfer> get activeTransfers => _transfers+ .where((t) => const {'scanning', 'waiting', 'active'}.contains(t.status))+ .toList();/// 所有正在传的批次合起来的进度(0–1);没有在传的为 nulldouble? get transferProgress {@@ -147,10 +166,17 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 正在发给这台设备的一批(雷达上的进度环)Transfer? sendingTo(String deviceId) => _transfers- .where((t) =>- t.direction == TransferDirection.TRANSFER_DIRECTION_OUTGOING &&- t.deviceId == deviceId &&- const {'scanning', 'waiting', 'active', 'queued'}.contains(t.status))+ .where(+ (t) =>+ t.direction == TransferDirection.TRANSFER_DIRECTION_OUTGOING &&+ t.deviceId == deviceId &&+ const {+ 'scanning',+ 'waiting',+ 'active',+ 'queued',+ }.contains(t.status),+ ).lastOrNull;String get pageRequest => _pageRequest;@@ -253,7 +279,10 @@ class AppState extends ChangeNotifier implements RecordDetails {// ─────────────────────────── 连接 ───────────────────────────- Future<void> connect() async {+ Future<void> connect() => _connectionWork = _connect();++ Future<void> _connect() async {+ if (_quitting) return;_retry?.cancel();_setLink(LinkState.connecting, null);await _replaceLegacyService();@@ -267,18 +296,26 @@ class AppState extends ChangeNotifier implements RecordDetails {conn.client.listHistory(ListHistoryRequest(limit: 200)),conn.client.getConfig(Empty()),conn.client.getStatus(Empty()),- conn.client.listHistory(ListHistoryRequest(limit: 500, favorites: true)),+ conn.client.listHistory(+ ListHistoryRequest(limit: 500, favorites: true),+ ),]);_records..clear()..addAll((results[0] as ListHistoryResponse).records);+ if (_quitting) {+ await conn.close();+ return;+ }_config = results[1] as Config;_status = results[2] as Status;// 旧版后台服务不认识 favorites,会把复制记录原样返回:只收下真的收藏_favorites..clear()- ..addAll((results[3] as ListHistoryResponse).records.where((r) => r.favorite));+ ..addAll(+ (results[3] as ListHistoryResponse).records.where((r) => r.favorite),+ );await _loadQuickPasteStatus();await _loadDevices();@@ -296,10 +333,24 @@ class AppState extends ChangeNotifier implements RecordDetails {_serviceState = null;_setLink(LinkState.online, null);- _ensureServiceCurrent();+ _maintenance = _ensureServiceCurrent();_historySearch.schedule(Duration.zero);_favoriteSearch.schedule(Duration.zero);} on DaemonNotRunning {+ if (!_sessionStartTried && service.available && !_quitting) {+ _sessionStartTried = true;+ try {+ final current = await service.state();+ if (current != ServiceState.mustMove &&+ current != ServiceState.unavailable) {+ await service.install();+ await _connect();+ return;+ }+ } catch (_) {+ /* Show the service page with a retry action. */+ }+ }await _refreshServiceState();_scheduleRetry(appL10n.linkServiceNotRunning);} catch (e) {@@ -316,7 +367,10 @@ class AppState extends ChangeNotifier implements RecordDetails {if (_legacyChecked || !service.available) return;_legacyChecked = true;try {- if (await service.removeLegacy()) await service.install();+ if (await service.removeLegacy()) {+ await service.setLaunchAtLogin(true);+ await service.install();+ }} catch (_) {// 清理失败不影响使用:用户还可以在界面上手动启用后台同步}@@ -335,7 +389,7 @@ class AppState extends ChangeNotifier implements RecordDetails {/// - 覆盖安装了新版 App:launchd 里跑的还是旧进程,按新的可执行文件重启/// 两种情况都会让当前连接断开,随后的自动重连会连上新进程。Future<void> _ensureServiceCurrent() async {- if (!service.available || _serviceChecked) return;+ if (!service.available || _serviceChecked || _quitting) return;_serviceChecked = true;try {final s = await service.state();@@ -353,6 +407,15 @@ class AppState extends ChangeNotifier implements RecordDetails {} catch (_) {// 核对失败不影响使用:旧进程仍在正常工作}+ if (_quitting) return;+ try {+ final enabled = await service.launchAtLogin();+ if (_config != null && _config!.launchAtLogin != enabled) {+ await updateConfig(_config!.deepCopy()..launchAtLogin = enabled);+ }+ } catch (_) {+ /* Keep the saved value if the OS query fails. */+ }await _syncQuickPaste();}@@ -360,7 +423,7 @@ class AppState extends ChangeNotifier implements RecordDetails {/// Windows、Linux 上快捷窗口由后台服务照看,这里什么都不做。Future<void> _syncQuickPaste() async {final qp = quickPasteService;- if (!qp.available) return;+ if (!qp.available || _quitting) return;try {// 快捷窗口跟着后台服务走:后台服务没登记成登录项(开发时手动跑的、测试用的)就不登记它if (await service.state() != ServiceState.running) return;@@ -370,7 +433,12 @@ class AppState extends ChangeNotifier implements RecordDetails {await qp.install();} else {final v = _quickPaste?.version ?? '';- if (appVersion != 'dev' && v.isNotEmpty && v != appVersion) await qp.restart();+ if (appVersion != 'dev' && v.isNotEmpty && v != appVersion) {+ await qp.restart();+ }+ }+ if (!(_config?.quickPasteDisabled ?? false)) {+ await qp.setLaunchAtLogin(await service.launchAtLogin());}} catch (_) {// 登记失败不影响主界面,设置页会显示快捷窗口没在运行@@ -429,6 +497,7 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 停用后台服务:关闭同步并取消开机自启。快捷窗口离了后台服务没法用,一起撤下,重新启用时再登记。Future<void> disableService() async {+ _sessionStartTried = true;_retry?.cancel();if (quickPasteService.available) await quickPasteService.uninstall();await service.uninstall();@@ -451,6 +520,7 @@ class AppState extends ChangeNotifier implements RecordDetails {}void _scheduleRetry(String message) {+ if (_quitting) return;_events?.cancel();_events = null;_conn?.close();@@ -479,7 +549,9 @@ class AppState extends ChangeNotifier implements RecordDetails {search.schedule(const Duration(milliseconds: 300));}// 取消收藏后同一条记录换到了复制记录里- (ev.clipAdded.favorite ? _historySearch : _favoriteSearch).remove(ev.clipAdded.id);+ (ev.clipAdded.favorite ? _historySearch : _favoriteSearch).remove(+ ev.clipAdded.id,+ );case Event_Payload.clipUpdated:_upsert(ev.clipUpdated);@@ -530,7 +602,9 @@ class AppState extends ChangeNotifier implements RecordDetails {}void _upsert(ClipRecord r) {- if (r.status == ClipStatus.CLIP_STATUS_FETCHING) _clipboardResults.remove(r.id);+ if (r.status == ClipStatus.CLIP_STATUS_FETCHING) {+ _clipboardResults.remove(r.id);+ }if (r.favorite) {_records.removeWhere((x) => x.id == r.id);final i = _favorites.indexWhere((x) => x.id == r.id);@@ -584,7 +658,9 @@ class AppState extends ChangeNotifier implements RecordDetails {if (i >= 0) {_transfers[i] = t;} else {- final at = _transfers.indexWhere((x) => x.createdAtUnix < t.createdAtUnix);+ final at = _transfers.indexWhere(+ (x) => x.createdAtUnix < t.createdAtUnix,+ );_transfers.insert(at < 0 ? _transfers.length : at, t);}}@@ -593,7 +669,9 @@ class AppState extends ChangeNotifier implements RecordDetails {final conn = _conn;if (conn == null) return;try {- final resp = await conn.client.listTransfers(ListTransfersRequest(limit: 500));+ final resp = await conn.client.listTransfers(+ ListTransfersRequest(limit: 500),+ );_transfers..clear()..addAll(resp.transfers);@@ -736,7 +814,56 @@ class AppState extends ChangeNotifier implements RecordDetails {_config = await _client.updateConfig(next);if (!wasOfficial && officialEnabled) _officialNavigationSerial++;notifyListeners();- if (_config!.quickPasteDisabled != quickPasteWasDisabled) await _syncQuickPaste();+ if (_config!.quickPasteDisabled != quickPasteWasDisabled) {+ await _syncQuickPaste();+ }+ }++ Future<void> setLaunchAtLogin(bool enabled) async {+ await service.setLaunchAtLogin(enabled);+ try {+ if (quickPasteService.available) {+ await quickPasteService.setLaunchAtLogin(+ enabled && !(config?.quickPasteDisabled ?? false),+ );+ }+ await updateConfig(config!.deepCopy()..launchAtLogin = enabled);+ } catch (_) {+ await service.setLaunchAtLogin(!enabled);+ if (quickPasteService.available) {+ await quickPasteService.setLaunchAtLogin(+ !enabled && !(config?.quickPasteDisabled ?? false),+ );+ }+ rethrow;+ }+ }++ Future<void> setPeerSync(String id, bool enabled) async {+ final next = config!.deepCopy();+ next.syncDisabledPeers.removeWhere((peer) => peer == id);+ if (!enabled) next.syncDisabledPeers.add(id);+ await updateConfig(next);+ }++ /// Stop helper jobs before the UI exits, preserving login entries.+ Future<void> quitApplication() async {+ _quitting = true;+ _retry?.cancel();+ try {+ await _connectionWork;+ await _maintenance;+ await _events?.cancel();+ _events = null;+ await _conn?.close();+ _conn = null;+ if (quickPasteService.available) await quickPasteService.stop();+ if (service.available) await service.stop();+ } catch (_) {+ _quitting = false;+ _scheduleRetry(appL10n.linkServiceDisconnected);+ rethrow;+ }}// ─────────────────────────── 更新 ───────────────────────────@@ -820,7 +947,9 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 给收藏起别名,[alias] 为空表示去掉。Future<ClipRecord> setAlias(String clipId, String alias) async {- final r = await _client.setAlias(SetAliasRequest(clipId: clipId, alias: alias));+ final r = await _client.setAlias(+ SetAliasRequest(clipId: clipId, alias: alias),+ );_upsert(r);_favoriteSearch.patch(r);notifyListeners();@@ -861,10 +990,12 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 输入搜索词。停顿一下再向后台服务查询,不必每敲一个字就查一次;空白表示不搜索。/// [notify] 为 false 用于页面销毁时清掉搜索:那时界面树已锁定,不能再通知重建。- void search(String query, {bool notify = true}) => _historySearch.set(query, notify: notify);+ void search(String query, {bool notify = true}) =>+ _historySearch.set(query, notify: notify);/// 收藏页的搜索,用法与 [search] 相同。- void searchFavorites(String query, {bool notify = true}) => _favoriteSearch.set(query, notify: notify);+ void searchFavorites(String query, {bool notify = true}) =>+ _favoriteSearch.set(query, notify: notify);/// 向后台服务搜索复制记录。界面测试与截图里由子类给出演示结果。@protected@@ -874,24 +1005,32 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 向后台服务搜索收藏。@protectedFuture<ListHistoryResponse> requestFavoriteSearch(String query) =>- _client.listHistory(ListHistoryRequest(limit: 200, query: query, favorites: true));+ _client.listHistory(+ ListHistoryRequest(limit: 200, query: query, favorites: true),+ );Future<void> refreshNotificationStatus() async {final conn = _conn;if (conn == null) return;try {- final status = await conn.client.getNotificationStatus(Empty(),- options: CallOptions(timeout: const Duration(seconds: 12)));+ final status = await conn.client.getNotificationStatus(+ Empty(),+ options: CallOptions(timeout: const Duration(seconds: 12)),+ );if (_conn == conn) _notificationStatus = status;} on GrpcError {- if (_conn == conn) _notificationStatus = NotificationStatus(permission: 'unavailable');+ if (_conn == conn) {+ _notificationStatus = NotificationStatus(permission: 'unavailable');+ }}if (_conn == conn) notifyListeners();}Future<void> requestNotifications() async {- _notificationStatus = await _client.requestNotificationPermission(Empty(),- options: CallOptions(timeout: const Duration(seconds: 20)));+ _notificationStatus = await _client.requestNotificationPermission(+ Empty(),+ options: CallOptions(timeout: const Duration(seconds: 20)),+ );notifyListeners();}@@ -918,26 +1057,41 @@ class AppState extends ChangeNotifier implements RecordDetails {// ─────────────────────────── 隔空传送 ───────────────────────────/// 把文件发给一台设备。要经官方服务中转而用户还没同意时抛出 SendFailure.needRelayConsent。- Future<Transfer> sendFiles(String deviceId, List<String> paths, {bool allowRelay = false}) async {+ Future<Transfer> sendFiles(+ String deviceId,+ List<String> paths, {+ bool allowRelay = false,+ }) async {final t = await _client.sendFiles(- SendFilesRequest(deviceId: deviceId, paths: paths, allowRelay: allowRelay),+ SendFilesRequest(+ deviceId: deviceId,+ paths: paths,+ allowRelay: allowRelay,+ ),);_upsertTransfer(t);notifyListeners();return t;}- Future<void> cancelTransfer(String id) => _client.cancelTransfer(TransferRef(id: id));+ Future<void> cancelTransfer(String id) =>+ _client.cancelTransfer(TransferRef(id: id));- Future<void> resumeTransfer(String id) => _client.resumeTransfer(TransferRef(id: id));+ Future<void> resumeTransfer(String id) =>+ _client.resumeTransfer(TransferRef(id: id));/// 只删记录,不删文件。- Future<void> deleteTransfers({List<String>? ids, TransferDirection? clearAll}) async {- await _client.deleteTransfers(DeleteTransfersRequest(- ids: ids ?? const [],- all: clearAll != null,- direction: clearAll ?? TransferDirection.TRANSFER_DIRECTION_UNSPECIFIED,- ));+ Future<void> deleteTransfers({+ List<String>? ids,+ TransferDirection? clearAll,+ }) async {+ await _client.deleteTransfers(+ DeleteTransfersRequest(+ ids: ids ?? const [],+ all: clearAll != null,+ direction: clearAll ?? TransferDirection.TRANSFER_DIRECTION_UNSPECIFIED,+ ),+ );}/// 打开隔空传送页时调用:侧边栏的数字清零。@@ -1001,7 +1155,11 @@ class AppState extends ChangeNotifier implements RecordDetails {/// 一组记录(复制记录或收藏)的搜索:搜索词、后台服务返回的结果,以及「只采用最后一次」的计数。class _RecordSearch {- _RecordSearch({required this.notify, required this.request, required this.local});+ _RecordSearch({+ required this.notify,+ required this.request,+ required this.local,+ });final VoidCallback notify;final Future<ListHistoryResponse> Function(String query) request;@@ -1015,7 +1173,8 @@ class _RecordSearch {int _seq = 0; // 只采用最后一次搜索的结果,先发出的请求可能后返回bool get active => query.trim().isNotEmpty;- List<ClipRecord>? get resultsView => _results == null ? null : List.unmodifiable(_results!);+ List<ClipRecord>? get resultsView =>+ _results == null ? null : List.unmodifiable(_results!);void set(String q, {bool notify = true}) {query = q;@@ -1042,7 +1201,9 @@ class _RecordSearch {try {final r = await request(q);// 旧版后台服务不认识搜索词,会原样返回全部记录:退回到只在已加载的记录里找- found = r.searched ? List.of(r.records) : local().where((x) => matchesSearch(x, q)).toList();+ found = r.searched+ ? List.of(r.records)+ : local().where((x) => matchesSearch(x, q)).toList();} catch (_) {found = local().where((x) => matchesSearch(x, q)).toList();}diff --git a/ui/lib/application_lifecycle.dart b/ui/lib/application_lifecycle.dartnew file mode 100644index 0000000..5417634--- /dev/null+++ b/ui/lib/application_lifecycle.dart@@ -0,0 +1,113 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import 'app_state.dart';+import 'i18n.dart';++final appNavigatorKey = GlobalKey<NavigatorState>();+const _channel = MethodChannel('com.pasteferry.app/lifecycle');+bool _busy = false;++void installApplicationLifecycle(AppState state) {+ _channel.setMethodCallHandler((call) async {+ final context = appNavigatorKey.currentContext;+ if (context == null) return;+ if (call.method == 'quitRequested') {+ await requestApplicationQuit(context, state);+ }+ if (call.method == 'closeRequested' && context.mounted) {+ await _closeWindow(context);+ }+ });+}++Future<void> requestApplicationQuit(+ BuildContext context,+ AppState state,+) async {+ if (_busy) return;+ _busy = true;+ try {+ if (state.activeTransfers.isNotEmpty) {+ final l = context.l10n;+ final confirmed = await showDialog<bool>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.quitApp),+ content: Text(l.quitTransfersWarning),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, true),+ child: Text(l.quitApp),+ ),+ ],+ ),+ );+ if (confirmed != true) return;+ }+ await state.quitApplication();+ exit(0);+ } catch (e) {+ if (context.mounted) {+ final l = context.l10n;+ await showDialog<void>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.quitApp),+ content: Text(AppState.describeError(e)),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx),+ child: Text(l.close),+ ),+ ],+ ),+ );+ }+ } finally {+ _busy = false;+ }+}++Future<void> _closeWindow(BuildContext context) async {+ if (_busy) return;+ _busy = true;+ try {+ final env = Platform.environment;+ final root = Platform.isWindows+ ? '${env['LOCALAPPDATA']}\\PasteFerry'+ : Platform.isMacOS+ ? '${env['HOME']}/Library/Application Support/PasteFerry'+ : '${env['XDG_DATA_HOME'] ?? '${env['HOME']}/.local/share'}/pasteferry';+ final marker = File('$root/window-close-notice');+ if (!await marker.exists() && context.mounted) {+ final l = context.l10n;+ await showDialog<void>(+ context: context,+ builder: (ctx) => AlertDialog(+ title: Text(l.backgroundRunningTitle),+ content: Text(l.backgroundRunningBody),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(ctx),+ child: Text(l.close),+ ),+ ],+ ),+ );+ await marker.parent.create(recursive: true);+ await marker.writeAsString('1');+ }+ await _channel.invokeMethod<void>('hideWindow');+ } on FileSystemException {+ await _channel.invokeMethod<void>('hideWindow');+ } finally {+ _busy = false;+ }+}diff --git a/ui/lib/background_service.dart b/ui/lib/background_service.dartindex 0be306b..832177d 100644--- a/ui/lib/background_service.dart+++ b/ui/lib/background_service.dart@@ -38,8 +38,8 @@ abstract class BackgroundService {factory BackgroundService() => Platform.isWindows? WindowsBackgroundService(): Platform.isLinux- ? LinuxBackgroundService()- : MacBackgroundService();+ ? LinuxBackgroundService()+ : MacBackgroundService();/// App 里是否带着后台服务(开发构建没有)bool get available;@@ -49,6 +49,14 @@ abstract class BackgroundService {Future<ServiceState> state();+ Future<bool> launchAtLogin();++ /// Changes the next-login entry without stopping the current session.+ Future<void> setLaunchAtLogin(bool enabled);++ /// Stops this session, preserving the next-login preference.+ Future<void> stop();+/// 注册并启动。重复调用即为修复。Future<void> install();@@ -67,11 +75,15 @@ abstract class BackgroundService {/// 注册成 launchd 的 LaunchAgent。/// 用 LaunchAgent 而非 LaunchDaemon:剪贴板属于登录用户的会话,系统级进程访问不到。class MacBackgroundService implements BackgroundService {- MacBackgroundService({String? executable, String? home})- : _executable = executable ?? Platform.resolvedExecutable,- _home = home ?? Platform.environment['HOME'] ?? '';+ MacBackgroundService({+ String? executable,+ String? home,+ this.serviceLabel = label,+ }) : _executable = executable ?? Platform.resolvedExecutable,+ _home = home ?? Platform.environment['HOME'] ?? '';static const label = 'com.pasteferry.daemon';+ final String serviceLabel;/// 界面 App 的 bundle ID。写进登录项,系统才知道后台服务属于哪个 App:/// macOS 15 的「本地网络」权限按它记账,登录项列表里也显示成 PasteFerry。@@ -85,11 +97,14 @@ class MacBackgroundService implements BackgroundService {String get helperApp => '$_bundle/Contents/Helpers/PasteFerryDaemon.app';String get helperBinary => '$helperApp/Contents/MacOS/pasteferryd';- String get plistPath => '$_home/Library/LaunchAgents/$label.plist';+ String get plistPath => '$_home/Library/LaunchAgents/$serviceLabel.plist';String get logPath => '$_home/Library/Logs/PasteFerry/daemon.log';+ String get runtimePath =>+ '$_home/Library/Application Support/PasteFerry/daemon.plist';@override- String get displayLogPath => logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~');+ String get displayLogPath =>+ logPath.replaceFirst(RegExp(r'^/Users/[^/]+'), '~');/// 旧版 install.sh 装在这里,迁移时清理掉String get _legacyApp => '$_home/Applications/CopySyncDaemon.app';@@ -104,19 +119,56 @@ class MacBackgroundService implements BackgroundService {Future<ServiceState> state() async {if (!available) return ServiceState.unavailable;if (_runningFromTemporaryLocation) return ServiceState.mustMove;- final plist = File(plistPath);- if (!await plist.exists()) return ServiceState.notInstalled;- final content = await plist.readAsString();- // 1.4.0 之前写的登录项没有 AssociatedBundleIdentifiers,重新写一份- if (!content.contains(helperBinary) || !content.contains(_appBundleId)) return ServiceState.stale;final r = await Process.run('launchctl', ['print', await _target()]);- if (r.exitCode != 0) return ServiceState.stopped;- return '${r.stdout}'.contains('state = running')+ final file = File(runtimePath).existsSync()+ ? File(runtimePath)+ : File(plistPath);+ if (!file.existsSync()) return ServiceState.notInstalled;+ if (!(await file.readAsString()).contains(_xml(helperBinary))) {+ return ServiceState.stale;+ }+ return r.exitCode == 0 && '${r.stdout}'.contains('state = running')? ServiceState.running: ServiceState.stopped;}- /// 注册并启动。重复调用即为修复:先注销旧的再重新注册。+ @override+ Future<bool> launchAtLogin() async => File(plistPath).existsSync();++ @override+ Future<void> setLaunchAtLogin(bool enabled) async {+ final file = File(plistPath);+ if (enabled) {+ await file.parent.create(recursive: true);+ await file.writeAsString(_plist());+ } else if (await file.exists()) {+ await file.delete();+ }+ }++ @override+ Future<void> stop() async {+ final before = await Process.run('launchctl', ['print', await _target()]);+ final pid = RegExp(+ r'^\s*pid = (\d+)',+ multiLine: true,+ ).firstMatch('${before.stdout}')?.group(1);+ await _bootout();+ if (pid != null) {+ for (var i = 0; i < 40; i++) {+ if ((await Process.run('kill', ['-0', pid])).exitCode != 0) break;+ await Future<void>.delayed(const Duration(milliseconds: 250));+ }+ if ((await Process.run('kill', ['-0', pid])).exitCode == 0) {+ throw ServiceException('The background process did not stop.');+ }+ }+ if ((await Process.run('launchctl', ['print', await _target()])).exitCode ==+ 0) {+ throw ServiceException('The background service did not stop.');+ }+ }+@overrideFuture<void> install() async {await _bootout();@@ -130,9 +182,15 @@ class MacBackgroundService implements BackgroundService {await Directory(File(plistPath).parent.path).create(recursive: true);await Directory(File(logPath).parent.path).create(recursive: true);- await File(plistPath).writeAsString(_plist());-- final r = await Process.run('launchctl', ['bootstrap', await _domain(), plistPath]);+ await File(runtimePath).parent.create(recursive: true);+ await File(runtimePath).writeAsString(_plist());+ if (await launchAtLogin()) await setLaunchAtLogin(true);++ final r = await Process.run('launchctl', [+ 'bootstrap',+ await _domain(),+ runtimePath,+ ]);if (r.exitCode != 0) {throw ServiceException(appL10n.errServiceStart('${r.stderr}'.trim()));}@@ -141,7 +199,11 @@ class MacBackgroundService implements BackgroundService {/// 让 launchd 结束旧进程并按当前的 App 重新拉起。用于 App 更新后。@overrideFuture<void> restart() async {- final r = await Process.run('launchctl', ['kickstart', '-k', await _target()]);+ final r = await Process.run('launchctl', [+ 'kickstart',+ '-k',+ await _target(),+ ]);if (r.exitCode != 0) {throw ServiceException(appL10n.errServiceRestart('${r.stderr}'.trim()));}@@ -150,7 +212,10 @@ class MacBackgroundService implements BackgroundService {/// 停用并移除登录项。数据目录保留,重新启用后历史记录与配对关系都还在。@overrideFuture<void> uninstall() async {- await _bootout();+ await stop();+ await setLaunchAtLogin(false);+ final runtime = File(runtimePath);+ if (await runtime.exists()) await runtime.delete();final plist = File(plistPath);if (await plist.exists()) await plist.delete();}@@ -181,14 +246,15 @@ class MacBackgroundService implements BackgroundService {return 'gui/$_uid';}- Future<String> _target() async => '${await _domain()}/$label';+ Future<String> _target() async => '${await _domain()}/$serviceLabel';- String _plist() => '''+ String _plist() =>+ '''<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>- <key>Label</key> <string>$label</string>+ <key>Label</key> <string>$serviceLabel</string><key>ProgramArguments</key><array><string>${_xml(helperBinary)}</string>@@ -207,8 +273,10 @@ class MacBackgroundService implements BackgroundService {</plist>''';- static String _xml(String s) =>- s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');+ static String _xml(String s) => s+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>');}class ServiceException implements Exception {diff --git a/ui/lib/background_service_linux.dart b/ui/lib/background_service_linux.dartindex ee5f21e..0beb1a8 100644--- a/ui/lib/background_service_linux.dart+++ b/ui/lib/background_service_linux.dart@@ -13,8 +13,8 @@ import 'i18n.dart';/// 不用 systemd 的用户服务:它不一定拿得到图形会话的环境变量,各发行版的做法也不一致。class LinuxBackgroundService implements BackgroundService {LinuxBackgroundService({String? executable, Map<String, String>? environment})- : _executable = executable ?? Platform.resolvedExecutable,- _env = environment ?? Platform.environment;+ : _executable = executable ?? Platform.resolvedExecutable,+ _env = environment ?? Platform.environment;static const _image = 'pasteferryd';@@ -31,12 +31,15 @@ class LinuxBackgroundService implements BackgroundService {return v.startsWith('/') ? v : '$_home/$fallback';}- String get autostartPath => '${_xdg('XDG_CONFIG_HOME', '.config')}/autostart/pasteferry-daemon.desktop';+ String get autostartPath =>+ '${_xdg('XDG_CONFIG_HOME', '.config')}/autostart/pasteferry-daemon.desktop';- String get logPath => '${_xdg('XDG_DATA_HOME', '.local/share')}/pasteferry/logs/daemon.log';+ String get logPath =>+ '${_xdg('XDG_DATA_HOME', '.local/share')}/pasteferry/logs/daemon.log';@override- String get displayLogPath => _home.isEmpty ? logPath : logPath.replaceFirst(_home, '~');+ String get displayLogPath =>+ _home.isEmpty ? logPath : logPath.replaceFirst(_home, '~');@overridebool get available => Platform.isLinux && File(daemonPath).existsSync();@@ -48,21 +51,40 @@ class LinuxBackgroundService implements BackgroundService {Future<ServiceState> state() async {if (!available) return ServiceState.unavailable;final file = File(autostartPath);- if (!file.existsSync()) return ServiceState.notInstalled;+ if (!file.existsSync()) {+ return await _running() ? ServiceState.running : ServiceState.stopped;+ }final exec = execLine(await file.readAsString());- if (exec == null || !exec.contains(quoteExecArg(daemonPath))) return ServiceState.stale;+ if (exec == null || !exec.contains(quoteExecArg(daemonPath))) {+ return ServiceState.stale;+ }return await _running() ? ServiceState.running : ServiceState.stopped;}@override- Future<void> install() async {+ Future<bool> launchAtLogin() async => File(autostartPath).existsSync();++ @override+ Future<void> setLaunchAtLogin(bool enabled) async {+ final file = File(autostartPath);+ if (!enabled) {+ if (await file.exists()) await file.delete();+ return;+ }try {- final file = File(autostartPath);await file.parent.create(recursive: true);await file.writeAsString(desktopEntry(_command));} on FileSystemException catch (e) {throw ServiceException(appL10n.errAutostart(e.message));}+ }++ @override+ Future<void> stop() => _stop();++ @override+ Future<void> install() async {+ if (await launchAtLogin()) await setLaunchAtLogin(true);await restart();}@@ -70,20 +92,23 @@ class LinuxBackgroundService implements BackgroundService {Future<void> restart() async {await _stop();// 脱离界面进程运行:关掉窗口后照常同步。环境变量随之传下去,后台服务才连得上剪贴板- await Process.start(daemonPath, ['-supervise'], mode: ProcessStartMode.detached);+ await Process.start(daemonPath, [+ '-supervise',+ ], mode: ProcessStartMode.detached);}@overrideFuture<void> uninstall() async {- final file = File(autostartPath);- if (file.existsSync()) await file.delete();- await _stop();+ await setLaunchAtLogin(false);+ await stop();}@overrideFuture<bool> removeLegacy() async {const legacyImage = 'copysyncd';- final old = File('${_xdg('XDG_CONFIG_HOME', '.config')}/autostart/copysync-daemon.desktop');+ final old = File(+ '${_xdg('XDG_CONFIG_HOME', '.config')}/autostart/copysync-daemon.desktop',+ );final enabled = old.existsSync();if (enabled) await old.delete();if (await _running(legacyImage)) await _stop(legacyImage);@@ -96,7 +121,9 @@ class LinuxBackgroundService implements BackgroundService {await Process.run('pkill', [..._ownedBy, '-x', image]);if (await _waitGone(image, 20)) return;await Process.run('pkill', ['-KILL', ..._ownedBy, '-x', image]);- await _waitGone(image, 8);+ if (!await _waitGone(image, 8)) {+ throw ServiceException('The background service did not stop.');+ }}Future<bool> _waitGone(String image, int checks) async {@@ -120,7 +147,8 @@ class LinuxBackgroundService implements BackgroundService {}/// XDG 自启动项。NoDisplay:不出现在应用菜单里;它只是后台服务的开机启动入口。-String desktopEntry(String exec) => '''[Desktop Entry]+String desktopEntry(String exec) =>+ '''[Desktop Entry]Type=ApplicationName=PasteFerryComment=Keeps the clipboard in sync with your other devices@@ -136,7 +164,9 @@ X-GNOME-Autostart-enabled=true/// 所以前三个写成两个反斜杠加原字符,反斜杠本身写成四个。String quoteExecArg(String arg) {final escaped = arg.replaceAllMapped(- RegExp(r'["`$\\]'), (m) => m[0] == r'\' ? r'\\\\' : r'\\' + m[0]!);+ RegExp(r'["`$\\]'),+ (m) => m[0] == r'\' ? r'\\\\' : r'\\' + m[0]!,+ );return '"$escaped"';}diff --git a/ui/lib/background_service_windows.dart b/ui/lib/background_service_windows.dartindex 22a5d94..61f2644 100644--- a/ui/lib/background_service_windows.dart+++ b/ui/lib/background_service_windows.dart@@ -11,9 +11,11 @@ import 'i18n.dart';////// 不做成 Windows 服务:服务运行在会话 0,与用户桌面隔离,访问不到用户的剪贴板。class WindowsBackgroundService implements BackgroundService {- WindowsBackgroundService({String? executable, Map<String, String>? environment})- : _executable = executable ?? Platform.resolvedExecutable,- _env = environment ?? Platform.environment;+ WindowsBackgroundService({+ String? executable,+ Map<String, String>? environment,+ }) : _executable = executable ?? Platform.resolvedExecutable,+ _env = environment ?? Platform.environment;static const _runKey = r'HKCU\Software\Microsoft\Windows\CurrentVersion\Run';static const _valueName = 'PasteFerry';@@ -27,12 +29,14 @@ class WindowsBackgroundService implements BackgroundService {/// 登记到自启项里的命令行String get _command => '"$daemonPath" -supervise';- String get _localAppData => _env['LOCALAPPDATA'] ?? '${_env['USERPROFILE']}\\AppData\\Local';+ String get _localAppData =>+ _env['LOCALAPPDATA'] ?? '${_env['USERPROFILE']}\\AppData\\Local';String get logPath => '$_localAppData\\PasteFerry\\logs\\daemon.log';@override- String get displayLogPath => logPath.replaceFirst(_localAppData, '%LOCALAPPDATA%');+ String get displayLogPath =>+ logPath.replaceFirst(_localAppData, '%LOCALAPPDATA%');@overridebool get available => Platform.isWindows && File(daemonPath).existsSync();@@ -50,19 +54,50 @@ class WindowsBackgroundService implements BackgroundService {if (!available) return ServiceState.unavailable;if (_runningFromTemporaryLocation) return ServiceState.mustMove;final registered = await _registeredCommand();- if (registered == null) return ServiceState.notInstalled;- if (!registered.toLowerCase().contains(daemonPath.toLowerCase())) return ServiceState.stale;+ if (registered == null) {+ return await _running() ? ServiceState.running : ServiceState.stopped;+ }+ if (!registered.toLowerCase().contains(daemonPath.toLowerCase())) {+ return ServiceState.stale;+ }return await _running() ? ServiceState.running : ServiceState.stopped;}@override- Future<void> install() async {+ Future<bool> launchAtLogin() async => await _registeredCommand() != null;++ @override+ Future<void> setLaunchAtLogin(bool enabled) async {+ if (!enabled) {+ await Process.run('reg', ['delete', _runKey, '/v', _valueName, '/f']);+ if (await launchAtLogin()) {+ throw ServiceException('Could not remove the login entry.');+ }+ return;+ }final r = await Process.run('reg', [- 'add', _runKey, '/v', _valueName, '/t', 'REG_SZ', '/d', _command, '/f', //+ 'add',+ _runKey,+ '/v',+ _valueName,+ '/t',+ 'REG_SZ',+ '/d',+ _command,+ '/f',]);if (r.exitCode != 0) {throw ServiceException(appL10n.errAutostart(_output(r)));}+ }++ @override+ Future<void> stop() => _stop();++ @override+ Future<void> install() async {+ // Preserve existing startup choices, including entries from older versions.+ if (await launchAtLogin()) await setLaunchAtLogin(true);await restart();}@@ -70,20 +105,31 @@ class WindowsBackgroundService implements BackgroundService {Future<void> restart() async {await _stop();// 脱离界面进程运行:关掉窗口后照常同步- await Process.start(daemonPath, ['-supervise'], mode: ProcessStartMode.detached);+ await Process.start(daemonPath, [+ '-supervise',+ ], mode: ProcessStartMode.detached);}@overrideFuture<void> uninstall() async {- await Process.run('reg', ['delete', _runKey, '/v', _valueName, '/f']);- await _stop();+ await setLaunchAtLogin(false);+ await stop();}@overrideFuture<bool> removeLegacy() async {const legacyValue = 'CopySync', legacyImage = 'copysyncd.exe';- final enabled = (await Process.run('reg', ['query', _runKey, '/v', legacyValue])).exitCode == 0;- if (enabled) await Process.run('reg', ['delete', _runKey, '/v', legacyValue, '/f']);+ final enabled =+ (await Process.run('reg', [+ 'query',+ _runKey,+ '/v',+ legacyValue,+ ])).exitCode ==+ 0;+ if (enabled) {+ await Process.run('reg', ['delete', _runKey, '/v', legacyValue, '/f']);+ }if (await _running(legacyImage)) await _stop(legacyImage);return enabled;}@@ -94,10 +140,17 @@ class WindowsBackgroundService implements BackgroundService {for (var i = 0; i < 20 && await _running(image); i++) {await Future<void>.delayed(const Duration(milliseconds: 250));}+ if (await _running(image)) {+ throw ServiceException('The background service did not stop.');+ }}Future<bool> _running([String image = _image]) async {- final r = await Process.run('tasklist', ['/FI', 'IMAGENAME eq $image', '/NH']);+ final r = await Process.run('tasklist', [+ '/FI',+ 'IMAGENAME eq $image',+ '/NH',+ ]);return '${r.stdout}'.toLowerCase().contains(image);}diff --git a/ui/lib/gen/pasteferry/v1/daemon.pb.dart b/ui/lib/gen/pasteferry/v1/daemon.pb.dartindex f49711e..2210f1c 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pb.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pb.dart@@ -2988,6 +2988,9 @@ class Config extends $pb.GeneratedMessage {$core.bool? receiveDisabled,$core.bool? receiveNotifyDisabled,$core.bool? sendLayoutStacked,+ $core.bool? realtimeSyncDisabled,+ $core.bool? syncBacklog,+ $core.Iterable<$core.String>? syncDisabledPeers,}) {final result = Config._();if (autoSyncThresholdBytes != null)@@ -3023,6 +3026,11 @@ class Config extends $pb.GeneratedMessage {if (receiveNotifyDisabled != null)result.receiveNotifyDisabled = receiveNotifyDisabled;if (sendLayoutStacked != null) result.sendLayoutStacked = sendLayoutStacked;+ if (realtimeSyncDisabled != null)+ result.realtimeSyncDisabled = realtimeSyncDisabled;+ if (syncBacklog != null) result.syncBacklog = syncBacklog;+ if (syncDisabledPeers != null)+ result.syncDisabledPeers.addAll(syncDisabledPeers);return result;}@@ -3066,6 +3074,9 @@ class Config extends $pb.GeneratedMessage {..aOB(24, _omitFieldNames ? '' : 'receiveDisabled')..aOB(25, _omitFieldNames ? '' : 'receiveNotifyDisabled')..aOB(26, _omitFieldNames ? '' : 'sendLayoutStacked')+ ..aOB(27, _omitFieldNames ? '' : 'realtimeSyncDisabled')+ ..aOB(28, _omitFieldNames ? '' : 'syncBacklog')+ ..pPS(29, _omitFieldNames ? '' : 'syncDisabledPeers')..hasRequiredFields = false;@$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.')@@ -3340,6 +3351,27 @@ class Config extends $pb.GeneratedMessage {$core.bool hasSendLayoutStacked() => $_has(25);@$pb.TagNumber(26)void clearSendLayoutStacked() => $_clearField(26);++ @$pb.TagNumber(27)+ $core.bool get realtimeSyncDisabled => $_getBF(26);+ @$pb.TagNumber(27)+ set realtimeSyncDisabled($core.bool value) => $_setBool(26, value);+ @$pb.TagNumber(27)+ $core.bool hasRealtimeSyncDisabled() => $_has(26);+ @$pb.TagNumber(27)+ void clearRealtimeSyncDisabled() => $_clearField(27);++ @$pb.TagNumber(28)+ $core.bool get syncBacklog => $_getBF(27);+ @$pb.TagNumber(28)+ set syncBacklog($core.bool value) => $_setBool(27, value);+ @$pb.TagNumber(28)+ $core.bool hasSyncBacklog() => $_has(27);+ @$pb.TagNumber(28)+ void clearSyncBacklog() => $_clearField(28);++ @$pb.TagNumber(29)+ $pb.PbList<$core.String> get syncDisabledPeers => $_getList(28);}class OfficialUsage extends $pb.GeneratedMessage {diff --git a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dartindex 6708e1a..fca632e 100644--- a/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart+++ b/ui/lib/gen/pasteferry/v1/daemon.pbjson.dart@@ -1001,6 +1001,21 @@ const Config$json = {'5': 8,'10': 'sendLayoutStacked'},+ {+ '1': 'realtime_sync_disabled',+ '3': 27,+ '4': 1,+ '5': 8,+ '10': 'realtimeSyncDisabled'+ },+ {'1': 'sync_backlog', '3': 28, '4': 1, '5': 8, '10': 'syncBacklog'},+ {+ '1': 'sync_disabled_peers',+ '3': 29,+ '4': 3,+ '5': 9,+ '10': 'syncDisabledPeers'+ },],};@@ -1026,7 +1041,9 @@ final $typed_data.Uint8List configDescriptor = $convert.base64Decode('B5T25seRIfCgtyZWNlaXZlX2RpchgXIAEoCVIKcmVjZWl2ZURpchIpChByZWNlaXZlX2Rpc2Fi''bGVkGBggASgIUg9yZWNlaXZlRGlzYWJsZWQSNgoXcmVjZWl2ZV9ub3RpZnlfZGlzYWJsZWQYGS''ABKAhSFXJlY2VpdmVOb3RpZnlEaXNhYmxlZBIuChNzZW5kX2xheW91dF9zdGFja2VkGBogASgI'- 'UhFzZW5kTGF5b3V0U3RhY2tlZA==');+ 'UhFzZW5kTGF5b3V0U3RhY2tlZBI0ChZyZWFsdGltZV9zeW5jX2Rpc2FibGVkGBsgASgIUhRyZW'+ 'FsdGltZVN5bmNEaXNhYmxlZBIhCgxzeW5jX2JhY2tsb2cYHCABKAhSC3N5bmNCYWNrbG9nEi4K'+ 'E3N5bmNfZGlzYWJsZWRfcGVlcnMYHSADKAlSEXN5bmNEaXNhYmxlZFBlZXJz');@$core.Deprecated('Use officialUsageDescriptor instead')const OfficialUsage$json = {diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arbindex 9901634..19ceaf4 100644--- a/ui/lib/l10n/app_en.arb+++ b/ui/lib/l10n/app_en.arb@@ -670,14 +670,14 @@"svcMoveTitle": "Move PasteFerry to Applications first","svcMoveBody": "PasteFerry is running straight from the disk image. Drag it into Applications, eject the disk image, and open it from Applications to turn on background sync.","svcStartTitle": "Get started with PasteFerry",- "svcStartBody": "PasteFerry runs a small background process that notices clipboard changes and stays connected to your other devices. Once on, it starts at login and keeps syncing even with this window closed.",+ "svcStartBody": "PasteFerry runs a small background process for clipboard sync. Closing the window keeps it running. Launch at login is a separate setting and is off for new installations.","svcEnable": "Turn on background sync","svcStaleTitle": "Turn background sync on again","svcStaleBodyWin": "PasteFerry has moved, but starting at login still points to the old place. Turn it on again so the background process uses this copy. History and pairings are kept.","svcStaleBodyMac": "PasteFerry has moved, or was installed with an old script. Turn it on again so the background process uses this app. History and pairings are kept.","svcReenable": "Turn on again","svcStoppedTitle": "The background service isn't running",- "svcStoppedBody": "It may have just quit; the system usually restarts it within seconds. If you stay on this page, restart it with the button below.",+ "svcStoppedBody": "The background service is stopped. Start it with the button below; launch at login is controlled separately in Settings.","svcDevBodyWin": "This is a development build with no pasteferryd.exe next to it. Run scripts\\build-windows.ps1 in the source folder to build a complete version.","svcDevBodyLinux": "This is a development build with no pasteferryd next to it. Run ./scripts/package-linux.sh in the source folder to build a complete version.","svcDevBodyMac": "This is a development build without the background service. Run ./scripts/install-macos.sh in the source folder to install it.",@@ -1294,5 +1294,19 @@"listSeparator": ", ","sendLayout": "Transfer list","sendLayoutSide": "Beside the radar",- "sendLayoutBelow": "Below the radar"+ "sendLayoutBelow": "Below the radar",+ "general": "General",+ "launchAtLogin": "Launch at login",+ "launchAtLoginDesc": "Start in the background when you log in. Changing this does not stop the current session.",+ "realtimeSync": "Real-time clipboard sync",+ "realtimeSyncDesc": "Automatically share new copies with paired devices. Local history and Send Files remain available when off.",+ "syncBacklog": "Catch up after reconnecting",+ "syncBacklogDesc": "Off by default: missed copies are skipped. When enabled, up to 20 copies from the last 24 hours enter history without replacing the clipboard.",+ "peerRealtimeSync": "Sync with this computer",+ "syncPaused": "Clipboard sync paused",+ "quitApp": "Quit PasteFerry",+ "quitAppDesc": "Stop all PasteFerry processes. Your launch-at-login preference is preserved.",+ "quitTransfersWarning": "Files are still being transferred. Quit and interrupt these transfers?",+ "backgroundRunningTitle": "PasteFerry will keep running",+ "backgroundRunningBody": "Closing the window keeps sync and quick paste running. To stop everything, choose Quit PasteFerry in Settings or the app menu."}diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arbindex a0b27fe..044cefe 100644--- a/ui/lib/l10n/app_ja.arb+++ b/ui/lib/l10n/app_ja.arb@@ -289,14 +289,14 @@"svcMoveTitle": "先に PasteFerry を「アプリケーション」に移動してください","svcMoveBody": "PasteFerry はディスクイメージから直接開かれています。「アプリケーション」にドラッグしてディスクイメージを取り出し、「アプリケーション」から開くと、バックグラウンド同期を有効にできます。","svcStartTitle": "PasteFerry を始める",- "svcStartBody": "PasteFerry は小さなバックグラウンドプロセスを動かし、クリップボードの変化を検知して他のデバイスとつながり続けます。有効にするとログイン時に起動し、このウィンドウを閉じても同期を続けます。",+ "svcStartBody": "PasteFerry はバックグラウンドでクリップボードを同期し、ウィンドウを閉じても動作します。ログイン時の起動は別の設定で、新規インストールではオフです。","svcEnable": "バックグラウンド同期を有効にする","svcStaleTitle": "バックグラウンド同期をもう一度有効にする","svcStaleBodyWin": "PasteFerry の場所が変わりましたが、自動起動は以前の場所を指しています。もう一度有効にすると、このコピーを使うようになります。履歴とペアリングは残ります。","svcStaleBodyMac": "PasteFerry の場所が変わったか、古いスクリプトでインストールされています。もう一度有効にすると、このアプリを使うようになります。履歴とペアリングは残ります。","svcReenable": "もう一度有効にする","svcStoppedTitle": "バックグラウンドサービスが動いていません",- "svcStoppedBody": "終了した直後かもしれません。通常は数秒で再起動されます。この画面のままなら、下のボタンで再起動してください。",+ "svcStoppedBody": "バックグラウンドサービスは停止しています。下のボタンで起動できます。ログイン時の起動は設定で個別に選べます。","svcDevBodyWin": "開発ビルドのため pasteferryd.exe がありません。ソースフォルダで scripts\\build-windows.ps1 を実行して完全版をビルドしてください。","svcDevBodyLinux": "開発ビルドのため pasteferryd がありません。ソースフォルダで ./scripts/package-linux.sh を実行して完全版をビルドしてください。","svcDevBodyMac": "開発ビルドのためバックグラウンドサービスが含まれていません。ソースフォルダで ./scripts/install-macos.sh を実行してインストールしてください。",@@ -498,5 +498,19 @@"listSeparator": "、","sendLayout": "転送リスト","sendLayoutSide": "レーダーの右",- "sendLayoutBelow": "レーダーの下"+ "sendLayoutBelow": "レーダーの下",+ "general": "一般",+ "launchAtLogin": "ログイン時に起動",+ "launchAtLoginDesc": "ログイン時にバックグラウンドで起動します。現在の動作は停止しません。",+ "realtimeSync": "クリップボードをリアルタイム同期",+ "realtimeSyncDesc": "新しくコピーした内容を自動共有します。オフでもローカル履歴とファイル送信は利用できます。",+ "syncBacklog": "再接続後に未送信の内容を同期",+ "syncBacklogDesc": "初期設定はオフです。オンにすると、24時間以内の未送信内容を最大20件、クリップボードを上書きせず履歴に追加します。",+ "peerRealtimeSync": "このパソコンと同期",+ "syncPaused": "同期を一時停止中",+ "quitApp": "PasteFerry を終了",+ "quitAppDesc": "すべてのプロセスを終了します。ログイン時の起動設定は保持されます。",+ "quitTransfersWarning": "ファイル転送中です。転送を中断して終了しますか?",+ "backgroundRunningTitle": "PasteFerry はバックグラウンドで動作します",+ "backgroundRunningBody": "ウィンドウを閉じても同期とクイック貼り付けは続きます。完全に停止するには、設定またはアプリメニューの「PasteFerry を終了」を選んでください。"}diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dartindex 82e4f99..70b1957 100644--- a/ui/lib/l10n/app_localizations.dart+++ b/ui/lib/l10n/app_localizations.dart@@ -1847,7 +1847,7 @@ abstract class AppLocalizations {/// No description provided for @svcStartBody.////// In en, this message translates to:- /// **'PasteFerry runs a small background process that notices clipboard changes and stays connected to your other devices. Once on, it starts at login and keeps syncing even with this window closed.'**+ /// **'PasteFerry runs a small background process for clipboard sync. Closing the window keeps it running. Launch at login is a separate setting and is off for new installations.'**String get svcStartBody;/// No description provided for @svcEnable.@@ -1889,7 +1889,7 @@ abstract class AppLocalizations {/// No description provided for @svcStoppedBody.////// In en, this message translates to:- /// **'It may have just quit; the system usually restarts it within seconds. If you stay on this page, restart it with the button below.'**+ /// **'The background service is stopped. Start it with the button below; launch at login is controlled separately in Settings.'**String get svcStoppedBody;/// No description provided for @svcDevBodyWin.@@ -3103,6 +3103,90 @@ abstract class AppLocalizations {/// In en, this message translates to:/// **'Below the radar'**String get sendLayoutBelow;++ /// No description provided for @general.+ ///+ /// In en, this message translates to:+ /// **'General'**+ String get general;++ /// No description provided for @launchAtLogin.+ ///+ /// In en, this message translates to:+ /// **'Launch at login'**+ String get launchAtLogin;++ /// No description provided for @launchAtLoginDesc.+ ///+ /// In en, this message translates to:+ /// **'Start in the background when you log in. Changing this does not stop the current session.'**+ String get launchAtLoginDesc;++ /// No description provided for @realtimeSync.+ ///+ /// In en, this message translates to:+ /// **'Real-time clipboard sync'**+ String get realtimeSync;++ /// No description provided for @realtimeSyncDesc.+ ///+ /// In en, this message translates to:+ /// **'Automatically share new copies with paired devices. Local history and Send Files remain available when off.'**+ String get realtimeSyncDesc;++ /// No description provided for @syncBacklog.+ ///+ /// In en, this message translates to:+ /// **'Catch up after reconnecting'**+ String get syncBacklog;++ /// No description provided for @syncBacklogDesc.+ ///+ /// In en, this message translates to:+ /// **'Off by default: missed copies are skipped. When enabled, up to 20 copies from the last 24 hours enter history without replacing the clipboard.'**+ String get syncBacklogDesc;++ /// No description provided for @peerRealtimeSync.+ ///+ /// In en, this message translates to:+ /// **'Sync with this computer'**+ String get peerRealtimeSync;++ /// No description provided for @syncPaused.+ ///+ /// In en, this message translates to:+ /// **'Clipboard sync paused'**+ String get syncPaused;++ /// No description provided for @quitApp.+ ///+ /// In en, this message translates to:+ /// **'Quit PasteFerry'**+ String get quitApp;++ /// No description provided for @quitAppDesc.+ ///+ /// In en, this message translates to:+ /// **'Stop all PasteFerry processes. Your launch-at-login preference is preserved.'**+ String get quitAppDesc;++ /// No description provided for @quitTransfersWarning.+ ///+ /// In en, this message translates to:+ /// **'Files are still being transferred. Quit and interrupt these transfers?'**+ String get quitTransfersWarning;++ /// No description provided for @backgroundRunningTitle.+ ///+ /// In en, this message translates to:+ /// **'PasteFerry will keep running'**+ String get backgroundRunningTitle;++ /// No description provided for @backgroundRunningBody.+ ///+ /// In en, this message translates to:+ /// **'Closing the window keeps sync and quick paste running. To stop everything, choose Quit PasteFerry in Settings or the app menu.'**+ String get backgroundRunningBody;}class _AppLocalizationsDelegatediff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dartindex b56c219..cb19d47 100644--- a/ui/lib/l10n/app_localizations_en.dart+++ b/ui/lib/l10n/app_localizations_en.dart@@ -1101,7 +1101,7 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get svcStartBody =>- 'PasteFerry runs a small background process that notices clipboard changes and stays connected to your other devices. Once on, it starts at login and keeps syncing even with this window closed.';+ 'PasteFerry runs a small background process for clipboard sync. Closing the window keeps it running. Launch at login is a separate setting and is off for new installations.';@overrideString get svcEnable => 'Turn on background sync';@@ -1125,7 +1125,7 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get svcStoppedBody =>- 'It may have just quit; the system usually restarts it within seconds. If you stay on this page, restart it with the button below.';+ 'The background service is stopped. Start it with the button below; launch at login is controlled separately in Settings.';@overrideString get svcDevBodyWin =>@@ -1903,4 +1903,52 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get sendLayoutBelow => 'Below the radar';++ @override+ String get general => 'General';++ @override+ String get launchAtLogin => 'Launch at login';++ @override+ String get launchAtLoginDesc =>+ 'Start in the background when you log in. Changing this does not stop the current session.';++ @override+ String get realtimeSync => 'Real-time clipboard sync';++ @override+ String get realtimeSyncDesc =>+ 'Automatically share new copies with paired devices. Local history and Send Files remain available when off.';++ @override+ String get syncBacklog => 'Catch up after reconnecting';++ @override+ String get syncBacklogDesc =>+ 'Off by default: missed copies are skipped. When enabled, up to 20 copies from the last 24 hours enter history without replacing the clipboard.';++ @override+ String get peerRealtimeSync => 'Sync with this computer';++ @override+ String get syncPaused => 'Clipboard sync paused';++ @override+ String get quitApp => 'Quit PasteFerry';++ @override+ String get quitAppDesc =>+ 'Stop all PasteFerry processes. Your launch-at-login preference is preserved.';++ @override+ String get quitTransfersWarning =>+ 'Files are still being transferred. Quit and interrupt these transfers?';++ @override+ String get backgroundRunningTitle => 'PasteFerry will keep running';++ @override+ String get backgroundRunningBody =>+ 'Closing the window keeps sync and quick paste running. To stop everything, choose Quit PasteFerry in Settings or the app menu.';}diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dartindex 18b9d62..01c5aef 100644--- a/ui/lib/l10n/app_localizations_ja.dart+++ b/ui/lib/l10n/app_localizations_ja.dart@@ -996,7 +996,7 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get svcStartBody =>- 'PasteFerry は小さなバックグラウンドプロセスを動かし、クリップボードの変化を検知して他のデバイスとつながり続けます。有効にするとログイン時に起動し、このウィンドウを閉じても同期を続けます。';+ 'PasteFerry はバックグラウンドでクリップボードを同期し、ウィンドウを閉じても動作します。ログイン時の起動は別の設定で、新規インストールではオフです。';@overrideString get svcEnable => 'バックグラウンド同期を有効にする';@@ -1020,7 +1020,7 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get svcStoppedBody =>- '終了した直後かもしれません。通常は数秒で再起動されます。この画面のままなら、下のボタンで再起動してください。';+ 'バックグラウンドサービスは停止しています。下のボタンで起動できます。ログイン時の起動は設定で個別に選べます。';@overrideString get svcDevBodyWin =>@@ -1748,4 +1748,48 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get sendLayoutBelow => 'レーダーの下';++ @override+ String get general => '一般';++ @override+ String get launchAtLogin => 'ログイン時に起動';++ @override+ String get launchAtLoginDesc => 'ログイン時にバックグラウンドで起動します。現在の動作は停止しません。';++ @override+ String get realtimeSync => 'クリップボードをリアルタイム同期';++ @override+ String get realtimeSyncDesc => '新しくコピーした内容を自動共有します。オフでもローカル履歴とファイル送信は利用できます。';++ @override+ String get syncBacklog => '再接続後に未送信の内容を同期';++ @override+ String get syncBacklogDesc =>+ '初期設定はオフです。オンにすると、24時間以内の未送信内容を最大20件、クリップボードを上書きせず履歴に追加します。';++ @override+ String get peerRealtimeSync => 'このパソコンと同期';++ @override+ String get syncPaused => '同期を一時停止中';++ @override+ String get quitApp => 'PasteFerry を終了';++ @override+ String get quitAppDesc => 'すべてのプロセスを終了します。ログイン時の起動設定は保持されます。';++ @override+ String get quitTransfersWarning => 'ファイル転送中です。転送を中断して終了しますか?';++ @override+ String get backgroundRunningTitle => 'PasteFerry はバックグラウンドで動作します';++ @override+ String get backgroundRunningBody =>+ 'ウィンドウを閉じても同期とクイック貼り付けは続きます。完全に停止するには、設定またはアプリメニューの「PasteFerry を終了」を選んでください。';}diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dartindex 0ffacc9..44b5a10 100644--- a/ui/lib/l10n/app_localizations_zh.dart+++ b/ui/lib/l10n/app_localizations_zh.dart@@ -987,8 +987,7 @@ class AppLocalizationsZh extends AppLocalizations {String get svcStartTitle => '开始使用隔空贴';@override- String get svcStartBody =>- '隔空贴会在后台运行一个小进程,用来感知剪贴板的变化,并与你的其他设备保持连接。启用后它随系统登录自动启动,关掉这个窗口也会照常同步。';+ String get svcStartBody => '隔空贴通过后台进程同步剪贴板,关闭窗口后仍会运行。开机启动可在设置里单独选择,新安装默认关闭。';@overrideString get svcEnable => '启用后台同步';@@ -1011,7 +1010,7 @@ class AppLocalizationsZh extends AppLocalizations {String get svcStoppedTitle => '后台服务没有运行';@override- String get svcStoppedBody => '它可能刚刚退出,系统通常会在几秒内把它重新拉起。如果一直停在这一页,点下面的按钮重新启动。';+ String get svcStoppedBody => '后台服务已停止。点下面的按钮启动;是否开机启动可在设置里单独选择。';@overrideString get svcDevBodyWin =>@@ -1729,6 +1728,50 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get sendLayoutBelow => '在雷达下面';++ @override+ String get general => '通用';++ @override+ String get launchAtLogin => '开机启动';++ @override+ String get launchAtLoginDesc => '登录电脑后在后台启动,不弹出主窗口。修改此项不会停止当前运行。';++ @override+ String get realtimeSync => '实时同步剪贴板';++ @override+ String get realtimeSyncDesc => '自动与配对设备同步新复制的内容。关闭后仍保存本机记录,也可手动隔空传送。';++ @override+ String get syncBacklog => '重连后补发离线内容';++ @override+ String get syncBacklogDesc =>+ '默认关闭:离线期间未送达的内容不再补发。开启后最多补发 24 小时内的 20 条记录,不覆盖当前剪贴板。';++ @override+ String get peerRealtimeSync => '与这台电脑实时同步';++ @override+ String get syncPaused => '剪贴板同步已暂停';++ @override+ String get quitApp => '退出隔空贴';++ @override+ String get quitAppDesc => '结束隔空贴的全部进程,保留开机启动设置。';++ @override+ String get quitTransfersWarning => '还有文件正在传输,是否中断传输并退出?';++ @override+ String get backgroundRunningTitle => '隔空贴将继续在后台运行';++ @override+ String get backgroundRunningBody =>+ '关闭窗口后,同步和快捷粘贴仍会运行。如需完全停止,请在设置或应用菜单选择「退出隔空贴」。';}/// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`).@@ -2714,8 +2757,7 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {String get svcStartTitle => '開始使用隔空貼';@override- String get svcStartBody =>- '隔空貼會在背景執行一個小型程序,用來偵測剪貼簿的變化,並與你的其他裝置保持連線。啟用後它會隨系統登入自動啟動,關閉這個視窗也會照常同步。';+ String get svcStartBody => '隔空貼透過背景程序同步剪貼簿,關閉視窗後仍會運作。開機啟動可在設定裏單獨選擇,新安裝預設關閉。';@overrideString get svcEnable => '啟用背景同步';@@ -2738,7 +2780,7 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {String get svcStoppedTitle => '背景服務沒有執行';@override- String get svcStoppedBody => '它可能剛剛結束,系統通常會在幾秒內重新啟動它。如果一直停留在這一頁,請按下面的按鈕重新啟動。';+ String get svcStoppedBody => '背景服務已停止。按下面的按鈕啟動;是否開機啟動可在設定裏單獨選擇。';@overrideString get svcDevBodyWin =>@@ -3456,6 +3498,50 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {@overrideString get sendLayoutBelow => '在雷達下面';++ @override+ String get general => '一般';++ @override+ String get launchAtLogin => '開機啟動';++ @override+ String get launchAtLoginDesc => '登入電腦後在背景啟動,不開啟主視窗。更改此項不會停止目前的運作。';++ @override+ String get realtimeSync => '即時同步剪貼簿';++ @override+ String get realtimeSyncDesc => '自動與配對裝置同步新複製的內容。關閉後仍保留本機記錄,也可手動隔空傳送。';++ @override+ String get syncBacklog => '重新連線後補傳離線內容';++ @override+ String get syncBacklogDesc =>+ '預設關閉:離線期間未送達的內容不再補傳。開啟後最多補傳 24 小時內的 20 筆記錄,不覆寫目前的剪貼簿。';++ @override+ String get peerRealtimeSync => '與這部電腦即時同步';++ @override+ String get syncPaused => '剪貼簿同步已暫停';++ @override+ String get quitApp => '退出隔空貼';++ @override+ String get quitAppDesc => '結束隔空貼的全部程序,保留開機啟動設定。';++ @override+ String get quitTransfersWarning => '還有檔案正在傳輸,要中斷傳輸並退出嗎?';++ @override+ String get backgroundRunningTitle => '隔空貼將繼續在背景運作';++ @override+ String get backgroundRunningBody =>+ '關閉視窗後,同步和快速貼上仍會運作。如需完全停止,請在設定或應用程式選單選擇「退出隔空貼」。';}/// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`).@@ -4441,8 +4527,7 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {String get svcStartTitle => '開始使用隔空貼';@override- String get svcStartBody =>- '隔空貼會在背景執行一個小程式,用來偵測剪貼簿的變化,並與你的其他裝置保持連線。啟用後它會隨系統登入自動啟動,關掉這個視窗也會照常同步。';+ String get svcStartBody => '隔空貼透過背景程序同步剪貼簿,關閉視窗後仍會執行。開機啟動可在設定裡單獨選擇,新安裝預設關閉。';@overrideString get svcEnable => '啟用背景同步';@@ -4465,7 +4550,7 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {String get svcStoppedTitle => '背景服務沒有在執行';@override- String get svcStoppedBody => '它可能剛剛結束,系統通常會在幾秒內把它重新啟動。如果一直停在這一頁,請點下面的按鈕重新啟動。';+ String get svcStoppedBody => '背景服務已停止。點下面的按鈕啟動;是否開機啟動可在設定裡單獨選擇。';@overrideString get svcDevBodyWin =>@@ -5183,4 +5268,48 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {@overrideString get sendLayoutBelow => '在雷達下面';++ @override+ String get general => '一般';++ @override+ String get launchAtLogin => '開機啟動';++ @override+ String get launchAtLoginDesc => '登入電腦後在背景啟動,不開啟主視窗。變更此項不會停止目前的執行。';++ @override+ String get realtimeSync => '即時同步剪貼簿';++ @override+ String get realtimeSyncDesc => '自動與配對裝置同步新複製的內容。關閉後仍保留本機記錄,也可手動隔空傳送。';++ @override+ String get syncBacklog => '重新連線後補傳離線內容';++ @override+ String get syncBacklogDesc =>+ '預設關閉:離線期間未送達的內容不再補傳。開啟後最多補傳 24 小時內的 20 筆記錄,不覆寫目前的剪貼簿。';++ @override+ String get peerRealtimeSync => '與這台電腦即時同步';++ @override+ String get syncPaused => '剪貼簿同步已暫停';++ @override+ String get quitApp => '結束隔空貼';++ @override+ String get quitAppDesc => '結束隔空貼的全部程序,保留開機啟動設定。';++ @override+ String get quitTransfersWarning => '還有檔案正在傳輸,要中斷傳輸並結束嗎?';++ @override+ String get backgroundRunningTitle => '隔空貼將繼續在背景執行';++ @override+ String get backgroundRunningBody =>+ '關閉視窗後,同步和快速貼上仍會執行。如需完全停止,請在設定或應用程式選單選擇「結束隔空貼」。';}diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arbindex 341d449..5eedb63 100644--- a/ui/lib/l10n/app_zh.arb+++ b/ui/lib/l10n/app_zh.arb@@ -289,14 +289,14 @@"svcMoveTitle": "先把隔空贴移到「应用程序」","svcMoveBody": "隔空贴现在是直接从安装盘里打开的。把它拖进「应用程序」文件夹,推出安装盘,再从「应用程序」里打开,就可以启用后台同步。","svcStartTitle": "开始使用隔空贴",- "svcStartBody": "隔空贴会在后台运行一个小进程,用来感知剪贴板的变化,并与你的其他设备保持连接。启用后它随系统登录自动启动,关掉这个窗口也会照常同步。",+ "svcStartBody": "隔空贴通过后台进程同步剪贴板,关闭窗口后仍会运行。开机启动可在设置里单独选择,新安装默认关闭。","svcEnable": "启用后台同步","svcStaleTitle": "重新启用后台同步","svcStaleBodyWin": "隔空贴换了位置,开机自启还指向原来的地方。重新启用一次,让后台进程指向当前这份隔空贴。历史记录与配对关系都会保留。","svcStaleBodyMac": "隔空贴换了位置,或者之前用旧版安装脚本装过。重新启用一次,让后台进程指向当前这个 App。历史记录与配对关系都会保留。","svcReenable": "重新启用","svcStoppedTitle": "后台服务没有运行",- "svcStoppedBody": "它可能刚刚退出,系统通常会在几秒内把它重新拉起。如果一直停在这一页,点下面的按钮重新启动。",+ "svcStoppedBody": "后台服务已停止。点下面的按钮启动;是否开机启动可在设置里单独选择。","svcDevBodyWin": "这是开发构建,旁边没有 pasteferryd.exe。在源码目录运行 scripts\\build-windows.ps1 构建完整的版本。","svcDevBodyLinux": "这是开发构建,旁边没有 pasteferryd。在源码目录运行 ./scripts/package-linux.sh 构建完整的版本。","svcDevBodyMac": "这是开发构建,App 里没有内置后台服务。在源码目录运行 ./scripts/install-macos.sh 安装它。",@@ -498,5 +498,19 @@"listSeparator": "、","sendLayout": "传输列表","sendLayoutSide": "在雷达右边",- "sendLayoutBelow": "在雷达下面"+ "sendLayoutBelow": "在雷达下面",+ "general": "通用",+ "launchAtLogin": "开机启动",+ "launchAtLoginDesc": "登录电脑后在后台启动,不弹出主窗口。修改此项不会停止当前运行。",+ "realtimeSync": "实时同步剪贴板",+ "realtimeSyncDesc": "自动与配对设备同步新复制的内容。关闭后仍保存本机记录,也可手动隔空传送。",+ "syncBacklog": "重连后补发离线内容",+ "syncBacklogDesc": "默认关闭:离线期间未送达的内容不再补发。开启后最多补发 24 小时内的 20 条记录,不覆盖当前剪贴板。",+ "peerRealtimeSync": "与这台电脑实时同步",+ "syncPaused": "剪贴板同步已暂停",+ "quitApp": "退出隔空贴",+ "quitAppDesc": "结束隔空贴的全部进程,保留开机启动设置。",+ "quitTransfersWarning": "还有文件正在传输,是否中断传输并退出?",+ "backgroundRunningTitle": "隔空贴将继续在后台运行",+ "backgroundRunningBody": "关闭窗口后,同步和快捷粘贴仍会运行。如需完全停止,请在设置或应用菜单选择「退出隔空贴」。"}diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arbindex e8270fd..a1a2941 100644--- a/ui/lib/l10n/app_zh_Hant_HK.arb+++ b/ui/lib/l10n/app_zh_Hant_HK.arb@@ -289,14 +289,14 @@"svcMoveTitle": "先把隔空貼移到「應用程式」","svcMoveBody": "隔空貼現在是直接從磁碟映像裏開啟的。把它拖進「應用程式」資料夾,推出磁碟映像,再從「應用程式」裏開啟,就可以啟用背景同步。","svcStartTitle": "開始使用隔空貼",- "svcStartBody": "隔空貼會在背景執行一個小型程序,用來偵測剪貼簿的變化,並與你的其他裝置保持連線。啟用後它會隨系統登入自動啟動,關閉這個視窗也會照常同步。",+ "svcStartBody": "隔空貼透過背景程序同步剪貼簿,關閉視窗後仍會運作。開機啟動可在設定裏單獨選擇,新安裝預設關閉。","svcEnable": "啟用背景同步","svcStaleTitle": "重新啟用背景同步","svcStaleBodyWin": "隔空貼換了位置,開機自動啟動仍指向原來的位置。重新啟用一次,讓背景程序指向目前這份隔空貼。歷史記錄與配對關係都會保留。","svcStaleBodyMac": "隔空貼換了位置,或者之前用舊版安裝腳本安裝過。重新啟用一次,讓背景程序指向目前這個 App。歷史記錄與配對關係都會保留。","svcReenable": "重新啟用","svcStoppedTitle": "背景服務沒有執行",- "svcStoppedBody": "它可能剛剛結束,系統通常會在幾秒內重新啟動它。如果一直停留在這一頁,請按下面的按鈕重新啟動。",+ "svcStoppedBody": "背景服務已停止。按下面的按鈕啟動;是否開機啟動可在設定裏單獨選擇。","svcDevBodyWin": "這是開發版本,旁邊沒有 pasteferryd.exe。在原始碼目錄執行 scripts\\build-windows.ps1 建置完整的版本。","svcDevBodyLinux": "這是開發版本,旁邊沒有 pasteferryd。在原始碼目錄執行 ./scripts/package-linux.sh 建置完整的版本。","svcDevBodyMac": "這是開發版本,App 裏沒有內建背景服務。在原始碼目錄執行 ./scripts/install-macos.sh 安裝它。",@@ -498,5 +498,19 @@"listSeparator": "、","sendLayout": "傳輸列表","sendLayoutSide": "在雷達右邊",- "sendLayoutBelow": "在雷達下面"+ "sendLayoutBelow": "在雷達下面",+ "general": "一般",+ "launchAtLogin": "開機啟動",+ "launchAtLoginDesc": "登入電腦後在背景啟動,不開啟主視窗。更改此項不會停止目前的運作。",+ "realtimeSync": "即時同步剪貼簿",+ "realtimeSyncDesc": "自動與配對裝置同步新複製的內容。關閉後仍保留本機記錄,也可手動隔空傳送。",+ "syncBacklog": "重新連線後補傳離線內容",+ "syncBacklogDesc": "預設關閉:離線期間未送達的內容不再補傳。開啟後最多補傳 24 小時內的 20 筆記錄,不覆寫目前的剪貼簿。",+ "peerRealtimeSync": "與這部電腦即時同步",+ "syncPaused": "剪貼簿同步已暫停",+ "quitApp": "退出隔空貼",+ "quitAppDesc": "結束隔空貼的全部程序,保留開機啟動設定。",+ "quitTransfersWarning": "還有檔案正在傳輸,要中斷傳輸並退出嗎?",+ "backgroundRunningTitle": "隔空貼將繼續在背景運作",+ "backgroundRunningBody": "關閉視窗後,同步和快速貼上仍會運作。如需完全停止,請在設定或應用程式選單選擇「退出隔空貼」。"}diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arbindex 0289dd1..4cbf047 100644--- a/ui/lib/l10n/app_zh_Hant_TW.arb+++ b/ui/lib/l10n/app_zh_Hant_TW.arb@@ -289,14 +289,14 @@"svcMoveTitle": "先把隔空貼移到「應用程式」","svcMoveBody": "隔空貼現在是直接從磁碟映像檔裡打開的。把它拖進「應用程式」資料夾,退出磁碟映像檔,再從「應用程式」裡打開,就可以啟用背景同步。","svcStartTitle": "開始使用隔空貼",- "svcStartBody": "隔空貼會在背景執行一個小程式,用來偵測剪貼簿的變化,並與你的其他裝置保持連線。啟用後它會隨系統登入自動啟動,關掉這個視窗也會照常同步。",+ "svcStartBody": "隔空貼透過背景程序同步剪貼簿,關閉視窗後仍會執行。開機啟動可在設定裡單獨選擇,新安裝預設關閉。","svcEnable": "啟用背景同步","svcStaleTitle": "重新啟用背景同步","svcStaleBodyWin": "隔空貼換了位置,開機自動啟動還指向原來的地方。重新啟用一次,讓背景程序指向目前這份隔空貼。歷史記錄與配對關係都會保留。","svcStaleBodyMac": "隔空貼換了位置,或者之前用舊版安裝腳本裝過。重新啟用一次,讓背景程序指向目前這個 App。歷史記錄與配對關係都會保留。","svcReenable": "重新啟用","svcStoppedTitle": "背景服務沒有在執行",- "svcStoppedBody": "它可能剛剛結束,系統通常會在幾秒內把它重新啟動。如果一直停在這一頁,請點下面的按鈕重新啟動。",+ "svcStoppedBody": "背景服務已停止。點下面的按鈕啟動;是否開機啟動可在設定裡單獨選擇。","svcDevBodyWin": "這是開發版本,旁邊沒有 pasteferryd.exe。在原始碼資料夾執行 scripts\\build-windows.ps1 建置完整的版本。","svcDevBodyLinux": "這是開發版本,旁邊沒有 pasteferryd。在原始碼資料夾執行 ./scripts/package-linux.sh 建置完整的版本。","svcDevBodyMac": "這是開發版本,App 裡沒有內建背景服務。在原始碼資料夾執行 ./scripts/install-macos.sh 安裝它。",@@ -498,5 +498,19 @@"listSeparator": "、","sendLayout": "傳輸列表","sendLayoutSide": "在雷達右邊",- "sendLayoutBelow": "在雷達下面"+ "sendLayoutBelow": "在雷達下面",+ "general": "一般",+ "launchAtLogin": "開機啟動",+ "launchAtLoginDesc": "登入電腦後在背景啟動,不開啟主視窗。變更此項不會停止目前的執行。",+ "realtimeSync": "即時同步剪貼簿",+ "realtimeSyncDesc": "自動與配對裝置同步新複製的內容。關閉後仍保留本機記錄,也可手動隔空傳送。",+ "syncBacklog": "重新連線後補傳離線內容",+ "syncBacklogDesc": "預設關閉:離線期間未送達的內容不再補傳。開啟後最多補傳 24 小時內的 20 筆記錄,不覆寫目前的剪貼簿。",+ "peerRealtimeSync": "與這台電腦即時同步",+ "syncPaused": "剪貼簿同步已暫停",+ "quitApp": "結束隔空貼",+ "quitAppDesc": "結束隔空貼的全部程序,保留開機啟動設定。",+ "quitTransfersWarning": "還有檔案正在傳輸,要中斷傳輸並結束嗎?",+ "backgroundRunningTitle": "隔空貼將繼續在背景執行",+ "backgroundRunningBody": "關閉視窗後,同步和快速貼上仍會執行。如需完全停止,請在設定或應用程式選單選擇「結束隔空貼」。"}diff --git a/ui/lib/main.dart b/ui/lib/main.dartindex d649e51..738f344 100644--- a/ui/lib/main.dart+++ b/ui/lib/main.dart@@ -3,6 +3,7 @@ import 'dart:io';import 'package:flutter/material.dart';import 'app_state.dart';+import 'application_lifecycle.dart';import 'gen/pasteferry/v1/daemon.pb.dart' show TransferDirection;import 'background_service.dart';import 'i18n.dart';@@ -49,6 +50,7 @@ class _PasteFerryAppState extends State<PasteFerryApp> {void initState() {super.initState();_state = widget.state ?? (AppState()..connect());+ if (widget.state == null) installApplicationLifecycle(_state);}@override@@ -84,6 +86,7 @@ class _PasteFerryAppState extends State<PasteFerryApp> {);return MaterialApp(title: 'PasteFerry',+ navigatorKey: appNavigatorKey,debugShowCheckedModeBanner: false,theme: light,darkTheme: dark,@@ -254,7 +257,8 @@ class _ShellState extends State<Shell> with WidgetsBindingObserver {// 自动更新后重新打开时提示一次结果final updated = state.lastUpdate;if (updated != null) {- final key = '${updated.fromVersion}>${updated.toVersion}@${updated.atUnix}';+ final key =+ '${updated.fromVersion}>${updated.toVersion}@${updated.atUnix}';if (key != _shownUpdateResult) {_shownUpdateResult = key;WidgetsBinding.instance.addPostFrameCallback((_) {@@ -262,7 +266,9 @@ class _ShellState extends State<Shell> with WidgetsBindingObserver {final l = context.l10n;showToast(context,- updated.ok ? l.updatedTo(updated.toVersion) : l.updateNotFinished(updated.fromVersion),+ updated.ok+ ? l.updatedTo(updated.toVersion)+ : l.updateNotFinished(updated.fromVersion),error: !updated.ok,);});@@ -351,7 +357,9 @@ class _Sidebar extends StatelessWidget {icon: AppIcons.star,label: l.navFavorites,selected: current == Section.favorites,- trailing: state.favorites.isEmpty ? null : '${state.favorites.length}',+ trailing: state.favorites.isEmpty+ ? null+ : '${state.favorites.length}',onTap: () => onSelect(Section.favorites),),_NavItem(@@ -479,12 +487,16 @@ class _SendBadge extends StatelessWidget {final active = state.activeTransfers;if (active.isEmpty) {final n = state.unseenTransfers;- return n == 0 ? const SizedBox.shrink() : Text('$n', style: context.text.labelSmall);+ return n == 0+ ? const SizedBox.shrink()+ : Text('$n', style: context.text.labelSmall);}final lines = [for (final t in active)() {- final percent = t.totalBytes > 0 ? '${(t.doneBytes.toInt() * 100 / t.totalBytes.toInt()).floor()}%' : '…';+ final percent = t.totalBytes > 0+ ? '${(t.doneBytes.toInt() * 100 / t.totalBytes.toInt()).floor()}%'+ : '…';return t.direction == TransferDirection.TRANSFER_DIRECTION_OUTGOING? l.sendingTo(t.deviceName, percent): l.receivingFrom(t.deviceName, percent);@@ -494,7 +506,10 @@ class _SendBadge extends StatelessWidget {message: lines.join('\n'),child: SizedBox.square(dimension: 12,- child: CircularProgressIndicator(strokeWidth: 1.6, value: state.transferProgress),+ child: CircularProgressIndicator(+ strokeWidth: 1.6,+ value: state.transferProgress,+ ),),);}diff --git a/ui/lib/pages/devices_page.dart b/ui/lib/pages/devices_page.dartindex 8d0d27f..1701bc0 100644--- a/ui/lib/pages/devices_page.dart+++ b/ui/lib/pages/devices_page.dart@@ -51,13 +51,20 @@ class DevicesPage extends StatelessWidget {),Expanded(child: ListView(- padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xl),+ padding: const EdgeInsets.fromLTRB(+ Insets.xl,+ 0,+ Insets.xl,+ Insets.xl,+ ),children: [if (state.self != null)GroupSection(title: Wording.thisDevice,footnote: l.thisDeviceFootnote(Wording.bothDevicesInText),- child: GroupBox(children: [_DeviceRow(device: state.self!, isSelf: true)]),+ child: GroupBox(+ children: [_DeviceRow(device: state.self!, isSelf: true)],+ ),),if (state.peers.isEmpty)Padding(@@ -90,7 +97,9 @@ class DevicesPage extends StatelessWidget {footnote: l.pairedFootnote,child: GroupBox(dividerIndent: 52,- children: [for (final d in state.peers) _DeviceRow(device: d)],+ children: [+ for (final d in state.peers) _DeviceRow(device: d),+ ],),),],@@ -113,7 +122,12 @@ class _DeviceRow extends StatelessWidget {Widget build(BuildContext context) {final p = context.palette;return Padding(- padding: const EdgeInsets.fromLTRB(Insets.lg, Insets.md, Insets.sm, Insets.md),+ padding: const EdgeInsets.fromLTRB(+ Insets.lg,+ Insets.md,+ Insets.sm,+ Insets.md,+ ),child: Row(children: [Icon(platformIcon(device.platform), size: 22, color: p.textDim),@@ -125,20 +139,62 @@ class _DeviceRow extends StatelessWidget {Text(device.name, style: context.text.labelLarge),const SizedBox(height: 2),Text(- device.publicKeyFingerprint,+ (AppScope.of(context).config?.realtimeSyncDisabled == true ||+ (AppScope.of(context).config?.syncDisabledPeers+ .contains(device.id) ??+ false)) &&+ !isSelf+ ? context.l10n.syncPaused+ : device.publicKeyFingerprint,// 等宽:用户要逐字符比对,等宽能显著降低看错的概率- style: context.text.bodySmall?.copyWith(fontFamily: monoFamily, letterSpacing: 0.4),+ style: context.text.bodySmall?.copyWith(+ fontFamily: monoFamily,+ letterSpacing: 0.4,+ ),),],),),+ if (!isSelf) ...[+ Tooltip(+ message: context.l10n.peerRealtimeSync,+ child: SmallSwitch(+ value:+ !(AppScope.of(+ context,+ ).config?.syncDisabledPeers.contains(device.id) ??+ false),+ onChanged: (v) async {+ try {+ await AppScope.read(context).setPeerSync(device.id, v);+ } catch (e) {+ if (context.mounted) {+ showToast(+ context,+ AppState.describeError(e),+ error: true,+ );+ }+ }+ },+ ),+ ),+ const SizedBox(width: Insets.md),+ ],if (isSelf)Padding(padding: const EdgeInsets.only(right: Insets.sm),- child: Text(context.l10n.thisDeviceShort, style: context.text.bodySmall),+ child: Text(+ context.l10n.thisDeviceShort,+ style: context.text.bodySmall,+ ),)else if (AppScope.of(context).isReconnecting(device.id)) ...[- const SizedBox(width: 12, height: 12, child: CircularProgressIndicator(strokeWidth: 2)),+ const SizedBox(+ width: 12,+ height: 12,+ child: CircularProgressIndicator(strokeWidth: 2),+ ),const SizedBox(width: Insets.xs + 2),Text(context.l10n.reconnecting, style: context.text.bodySmall),const SizedBox(width: Insets.sm),@@ -146,7 +202,9 @@ class _DeviceRow extends StatelessWidget {] else ...[StatusDot(color: device.online ? p.online : p.textFaint,- label: device.online ? connectionLabel(device) : context.l10n.offline,+ label: device.online+ ? connectionLabel(device)+ : context.l10n.offline,),const SizedBox(width: Insets.sm),_DeviceMenu(device: device),@@ -158,15 +216,15 @@ class _DeviceRow extends StatelessWidget {}String connectionLabel(Device d) => switch (d.connection) {- ConnectionKind.CONNECTION_KIND_DIRECT => appL10n.direct,- ConnectionKind.CONNECTION_KIND_RELAY => appL10n.relay,- _ => appL10n.online,- };+ ConnectionKind.CONNECTION_KIND_DIRECT => appL10n.direct,+ ConnectionKind.CONNECTION_KIND_RELAY => appL10n.relay,+ _ => appL10n.online,+};IconData platformIcon(String platform) => switch (platform) {- 'windows' || 'linux' => AppIcons.desktopComputer,- _ => AppIcons.deviceLaptop,- };+ 'windows' || 'linux' => AppIcons.desktopComputer,+ _ => AppIcons.deviceLaptop,+};class _DeviceMenu extends StatelessWidget {const _DeviceMenu({required this.device});@@ -184,15 +242,30 @@ class _DeviceMenu extends StatelessWidget {// 已是直连就不用了;中转时马上再试一次直连,离线时马上去找它if (device.connection != ConnectionKind.CONNECTION_KIND_DIRECT &&!AppScope.read(ctx).isReconnecting(device.id))- PopupMenuItem(value: 'reconnect', height: 34, child: Text(l.reconnect)),- PopupMenuItem(value: 'copy', height: 34, child: Text(l.copyFingerprint)),+ PopupMenuItem(+ value: 'reconnect',+ height: 34,+ child: Text(l.reconnect),+ ),+ PopupMenuItem(+ value: 'copy',+ height: 34,+ child: Text(l.copyFingerprint),+ ),// 局域网里找不到对方时(跨网段、两边都换了地址),手动告诉后台服务去哪里找if (!device.online)- PopupMenuItem(value: 'address', height: 34, child: Text(l.enterAddressEllipsis)),+ PopupMenuItem(+ value: 'address',+ height: 34,+ child: Text(l.enterAddressEllipsis),+ ),PopupMenuItem(value: 'unpair',height: 34,- child: Text(l.unpairEllipsis, style: TextStyle(color: ctx.palette.danger)),+ child: Text(+ l.unpairEllipsis,+ style: TextStyle(color: ctx.palette.danger),+ ),),],onSelected: (v) => switch (v) {@@ -217,14 +290,18 @@ class _DeviceMenu extends StatelessWidget {switch (kind) {ConnectionKind.CONNECTION_KIND_DIRECT => l.reconnectDirect,ConnectionKind.CONNECTION_KIND_RELAY => l.reconnectRelay,- ConnectionKind.CONNECTION_KIND_OFFLINE => l.reconnectOffline(device.name),+ ConnectionKind.CONNECTION_KIND_OFFLINE => l.reconnectOffline(+ device.name,+ ),_ => l.reconnectPending,},// 没连上直连就不打对勾:仍经中转、对方不在线都用提醒的样式error: kind != ConnectionKind.CONNECTION_KIND_DIRECT,);} catch (e) {- if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ if (context.mounted) {+ showToast(context, AppState.describeError(e), error: true);+ }}}@@ -260,8 +337,14 @@ class _DeviceMenu extends StatelessWidget {),),actions: [- OutlinedButton(onPressed: () => Navigator.pop(ctx), child: Text(l.cancel)),- FilledButton(onPressed: () => Navigator.pop(ctx, controller.text), child: Text(l.save)),+ OutlinedButton(+ onPressed: () => Navigator.pop(ctx),+ child: Text(l.cancel),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(ctx, controller.text),+ child: Text(l.save),+ ),],),);@@ -273,15 +356,11 @@ class _DeviceMenu extends StatelessWidget {} catch (e) {if (!context.mounted) return;final failure = AppState.pairingFailure(e);- showToast(- context,- switch (failure) {- PairingFailure.badAddress => l.addressInvalid,- PairingFailure.noChannel => l.pairNoChannel,- _ => AppState.describeError(e),- },- error: true,- );+ showToast(context, switch (failure) {+ PairingFailure.badAddress => l.addressInvalid,+ PairingFailure.noChannel => l.pairNoChannel,+ _ => AppState.describeError(e),+ }, error: true);}}@@ -294,7 +373,10 @@ class _DeviceMenu extends StatelessWidget {title: Text(l.unpairTitle(device.name)),content: Text(l.unpairBody),actions: [- OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),+ OutlinedButton(+ onPressed: () => Navigator.pop(ctx, false),+ child: Text(l.cancel),+ ),FilledButton(onPressed: () => Navigator.pop(ctx, true),style: FilledButton.styleFrom(backgroundColor: ctx.palette.danger),@@ -308,7 +390,9 @@ class _DeviceMenu extends StatelessWidget {await state.unpair(device.id);if (context.mounted) showToast(context, l.unpaired);} catch (e) {- if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ if (context.mounted) {+ showToast(context, AppState.describeError(e), error: true);+ }}}}@@ -328,7 +412,9 @@ class LanBlockedNotice extends StatelessWidget {try {await AppScope.read(context).requestLocalNetworkPermission();} catch (e) {- if (context.mounted) showToast(context, AppState.describeError(e), error: true);+ if (context.mounted) {+ showToast(context, AppState.describeError(e), error: true);+ }}},child: Text(l.openSystemSettings),diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dartindex 495c8ee..fa91e99 100644--- a/ui/lib/pages/settings_page.dart+++ b/ui/lib/pages/settings_page.dart@@ -4,6 +4,7 @@ import 'package:fixnum/fixnum.dart';import 'package:flutter/material.dart';import '../app_state.dart';+import '../application_lifecycle.dart';import '../background_service.dart';import '../gen/pasteferry/v1/daemon.pb.dart';import '../i18n.dart';@@ -29,6 +30,7 @@ class _SettingsPageState extends State<SettingsPage> {final _nameController = TextEditingController();bool _serverDirty = false;bool _serverSaving = false;+ bool _startupSaving = false;bool _nameDirty = false;String? _lastLoadedServer;String? _lastLoadedName;@@ -93,6 +95,48 @@ class _SettingsPageState extends State<SettingsPage> {Insets.xxl,),children: [+ GroupSection(+ title: l.general,+ child: GroupBox(+ children: [+ SettingRow(+ title: l.launchAtLogin,+ description: l.launchAtLoginDesc,+ child: SmallSwitch(+ value: cfg.launchAtLogin,+ onChanged: _startupSaving || !state.service.available+ ? null+ : (v) async {+ setState(() => _startupSaving = true);+ try {+ await state.setLaunchAtLogin(v);+ } catch (e) {+ if (context.mounted) {+ showToast(+ context,+ AppState.describeError(e),+ error: true,+ );+ }+ } finally {+ if (mounted) {+ setState(() => _startupSaving = false);+ }+ }+ },+ ),+ ),+ SettingRow(+ title: l.quitApp,+ description: l.quitAppDesc,+ child: OutlinedButton(+ onPressed: () => requestApplicationQuit(context, state),+ child: Text(l.quitApp),+ ),+ ),+ ],+ ),+ ),GroupSection(title: l.server,child: GroupBox(@@ -237,11 +281,34 @@ class _SettingsPageState extends State<SettingsPage> {],),),- QuickPasteSection(config: cfg, onUpdate: (next) => _update(state, next)),+ QuickPasteSection(+ config: cfg,+ onUpdate: (next) => _update(state, next),+ ),GroupSection(title: l.sync,child: GroupBox(children: [+ SettingRow(+ title: l.realtimeSync,+ description: l.realtimeSyncDesc,+ child: SmallSwitch(+ value: !cfg.realtimeSyncDisabled,+ onChanged: (v) => _update(+ state,+ cfg.deepCopy()..realtimeSyncDisabled = !v,+ ),+ ),+ ),+ SettingRow(+ title: l.syncBacklog,+ description: l.syncBacklogDesc,+ child: SmallSwitch(+ value: cfg.syncBacklog,+ onChanged: (v) =>+ _update(state, cfg.deepCopy()..syncBacklog = v),+ ),+ ),SettingRow(title: l.autoSyncLimit,description: l.autoSyncLimitDesc,@@ -305,7 +372,10 @@ class _SettingsPageState extends State<SettingsPage> {],),),- SendSection(config: cfg, onUpdate: (next) => _update(state, next)),+ SendSection(+ config: cfg,+ onUpdate: (next) => _update(state, next),+ ),GroupSection(title: l.whatToSync,child: GroupBox(@@ -370,7 +440,9 @@ class _SettingsPageState extends State<SettingsPage> {description: l.favoritesUsageDesc,child: Text(l.upToSize(humanBytes(state.favoritesBytes)),- style: context.text.bodyMedium?.copyWith(color: p.textDim),+ style: context.text.bodyMedium?.copyWith(+ color: p.textDim,+ ),),),],@@ -441,7 +513,8 @@ class _SettingsPageState extends State<SettingsPage> {const SizedBox(width: Insets.sm),SmallSwitch(value: !cfg.updateCheckDisabled,- onChanged: (v) => _update(state, cfg..updateCheckDisabled = !v),+ onChanged: (v) =>+ _update(state, cfg..updateCheckDisabled = !v),),],),diff --git a/ui/lib/quick_paste_service.dart b/ui/lib/quick_paste_service.dartindex dc887aa..f842a37 100644--- a/ui/lib/quick_paste_service.dart+++ b/ui/lib/quick_paste_service.dart@@ -9,7 +9,8 @@ import 'hotkey.dart';/// 不能让后台服务直接拉起它,系统按拉起它的进程记辅助功能权限,授权列表里会显示成后台服务。/// Windows、Linux 上快捷窗口由后台服务拉起(界面程序加 --picker),这里什么都不做。abstract class QuickPasteService {- factory QuickPasteService() => Platform.isMacOS ? MacQuickPasteService() : const _ManagedByDaemon();+ factory QuickPasteService() =>+ Platform.isMacOS ? MacQuickPasteService() : const _ManagedByDaemon();/// App 里带着快捷窗口(开发构建没有)bool get available;@@ -25,6 +26,8 @@ abstract class QuickPasteService {/// 按当前的 App 重新拉起。用于 App 更新后Future<void> restart();+ Future<void> stop();+ Future<void> setLaunchAtLogin(bool enabled);}class _ManagedByDaemon implements QuickPasteService {@@ -39,12 +42,16 @@ class _ManagedByDaemon implements QuickPasteService {Future<void> uninstall() async {}@overrideFuture<void> restart() async {}+ @override+ Future<void> stop() async {}+ @override+ Future<void> setLaunchAtLogin(bool enabled) async {}}class MacQuickPasteService implements QuickPasteService {MacQuickPasteService({String? executable, String? home})- : _executable = executable ?? Platform.resolvedExecutable,- _home = home ?? Platform.environment['HOME'] ?? '';+ : _executable = executable ?? Platform.resolvedExecutable,+ _home = home ?? Platform.environment['HOME'] ?? '';static const label = 'com.pasteferry.picker';static const _appBundleId = 'com.pasteferry.app';@@ -55,35 +62,76 @@ class MacQuickPasteService implements QuickPasteService {/// `…/PasteFerry.app`,由可执行文件 `…/PasteFerry.app/Contents/MacOS/PasteFerry` 上溯三级。String get _bundle => File(_executable).parent.parent.parent.path;- String get helperBinary => '$_bundle/Contents/Helpers/PasteFerryPicker.app/Contents/MacOS/PasteFerryPicker';+ String get helperBinary =>+ '$_bundle/Contents/Helpers/PasteFerryPicker.app/Contents/MacOS/PasteFerryPicker';String get plistPath => '$_home/Library/LaunchAgents/$label.plist';String get logPath => '$_home/Library/Logs/PasteFerry/picker.log';+ String get runtimePath =>+ '$_home/Library/Application Support/PasteFerry/picker.plist';@override- bool get available => File(helperBinary).existsSync() && !_bundle.startsWith('/Volumes/');+ bool get available =>+ File(helperBinary).existsSync() && !_bundle.startsWith('/Volumes/');@overrideFuture<bool> installed() async {- final plist = File(plistPath);+ final plist = File(runtimePath).existsSync()+ ? File(runtimePath)+ : File(plistPath);if (!await plist.exists()) return false;if (!(await plist.readAsString()).contains(helperBinary)) return false;- return (await Process.run('launchctl', ['print', await _target()])).exitCode == 0;+ return (await Process.run('launchctl', [+ 'print',+ await _target(),+ ])).exitCode ==+ 0;}@overrideFuture<void> install() async {await _bootout();- await Process.run('xattr', ['-dr', 'com.apple.quarantine', File(helperBinary).parent.parent.parent.path]);+ await Process.run('xattr', [+ '-dr',+ 'com.apple.quarantine',+ File(helperBinary).parent.parent.parent.path,+ ]);await Directory(File(plistPath).parent.path).create(recursive: true);await Directory(File(logPath).parent.path).create(recursive: true);- await File(plistPath).writeAsString(_plist());- final r = await Process.run('launchctl', ['bootstrap', await _domain(), plistPath]);+ await File(runtimePath).parent.create(recursive: true);+ await File(runtimePath).writeAsString(_plist());+ final r = await Process.run('launchctl', [+ 'bootstrap',+ await _domain(),+ runtimePath,+ ]);if (r.exitCode != 0) throw ServiceException('${r.stderr}'.trim());}@override- Future<void> uninstall() async {+ Future<void> stop() async {await _bootout();+ if ((await Process.run('launchctl', ['print', await _target()])).exitCode ==+ 0) {+ throw ServiceException('The quick paste service did not stop.');+ }+ }++ @override+ Future<void> setLaunchAtLogin(bool enabled) async {+ final file = File(plistPath);+ if (enabled) {+ await file.parent.create(recursive: true);+ await file.writeAsString(_plist());+ } else if (await file.exists()) {+ await file.delete();+ }+ }++ @override+ Future<void> uninstall() async {+ await stop();+ final runtime = File(runtimePath);+ if (await runtime.exists()) await runtime.delete();final plist = File(plistPath);if (await plist.exists()) await plist.delete();}@@ -97,7 +145,9 @@ class MacQuickPasteService implements QuickPasteService {final target = await _target();await Process.run('launchctl', ['bootout', target]);for (var i = 0; i < 20; i++) {- if ((await Process.run('launchctl', ['print', target])).exitCode != 0) return;+ if ((await Process.run('launchctl', ['print', target])).exitCode != 0) {+ return;+ }await Future<void>.delayed(const Duration(milliseconds: 250));}}@@ -111,7 +161,8 @@ class MacQuickPasteService implements QuickPasteService {Future<String> _target() async => '${await _domain()}/$label';// 只在异常退出时重启:快捷粘贴被关掉时它自己正常退出,不该再被拉起来- String _plist() => '''+ String _plist() =>+ '''<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0">@@ -139,7 +190,10 @@ class MacQuickPasteService implements QuickPasteService {</plist>''';- static String _xml(String s) => s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');+ static String _xml(String s) => s+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>');}/// Linux Wayland 上没有全局快捷键门户时(如 Ubuntu 24.04 的 GNOME 46),@@ -147,39 +201,78 @@ class MacQuickPasteService implements QuickPasteService {/// 它会交给已经在运行的快捷窗口显示或收起(见 linux/runner/picker_application.cc),几乎没有延迟。abstract final class GnomeShortcut {static const _schema = 'org.gnome.settings-daemon.plugins.media-keys';- static const _path = '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/pasteferry/';+ static const _path =+ '/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/pasteferry/';static bool get supported =>- Platform.isLinux && (Platform.environment['XDG_CURRENT_DESKTOP'] ?? '').toUpperCase().contains('GNOME');+ Platform.isLinux &&+ (Platform.environment['XDG_CURRENT_DESKTOP'] ?? '')+ .toUpperCase()+ .contains('GNOME');/// 呼出快捷窗口的命令- static String get command => '${Platform.resolvedExecutable} --picker --toggle';+ static String get command =>+ '${Platform.resolvedExecutable} --picker --toggle';/// GNOME 的写法:`<Alt>v`、`<Primary><Shift>v`、`<Super>v`。static String binding(Hotkey h) {- const names = {'ctrl': '<Primary>', 'alt': '<Alt>', 'shift': '<Shift>', 'meta': '<Super>'};+ const names = {+ 'ctrl': '<Primary>',+ 'alt': '<Alt>',+ 'shift': '<Shift>',+ 'meta': '<Super>',+ };const keys = {- 'space': 'space', 'tab': 'Tab', 'enter': 'Return', 'backspace': 'BackSpace', 'delete': 'Delete',- 'insert': 'Insert', 'home': 'Home', 'end': 'End', 'pageup': 'Page_Up', 'pagedown': 'Page_Down',- 'up': 'Up', 'down': 'Down', 'left': 'Left', 'right': 'Right', 'quote': 'apostrophe',+ 'space': 'space',+ 'tab': 'Tab',+ 'enter': 'Return',+ 'backspace': 'BackSpace',+ 'delete': 'Delete',+ 'insert': 'Insert',+ 'home': 'Home',+ 'end': 'End',+ 'pageup': 'Page_Up',+ 'pagedown': 'Page_Down',+ 'up': 'Up',+ 'down': 'Down',+ 'left': 'Left',+ 'right': 'Right',+ 'quote': 'apostrophe','backquote': 'grave',};- final key = keys[h.key] ?? (Hotkey.isFunctionKey(h.key) ? h.key.toUpperCase() : h.key);+ final key =+ keys[h.key] ??+ (Hotkey.isFunctionKey(h.key) ? h.key.toUpperCase() : h.key);return '${h.modifiers.map((m) => names[m]).join()}$key';}/// 添加或更新这条自定义快捷键。static Future<void> install(Hotkey h) async {final key = '$_schema.custom-keybinding:$_path';- for (final (k, v) in [('name', 'PasteFerry'), ('command', command), ('binding', binding(h))]) {+ for (final (k, v) in [+ ('name', 'PasteFerry'),+ ('command', command),+ ('binding', binding(h)),+ ]) {final r = await Process.run('gsettings', ['set', key, k, v]);if (r.exitCode != 0) throw ServiceException('${r.stderr}'.trim());}- final list = await Process.run('gsettings', ['get', _schema, 'custom-keybindings']);- final current = RegExp(r"'([^']+)'").allMatches('${list.stdout}').map((m) => m.group(1)!).toList();+ final list = await Process.run('gsettings', [+ 'get',+ _schema,+ 'custom-keybindings',+ ]);+ final current = RegExp(+ r"'([^']+)'",+ ).allMatches('${list.stdout}').map((m) => m.group(1)!).toList();if (!current.contains(_path)) {final next = [...current, _path].map((p) => "'$p'").join(', ');- final r = await Process.run('gsettings', ['set', _schema, 'custom-keybindings', '[$next]']);+ final r = await Process.run('gsettings', [+ 'set',+ _schema,+ 'custom-keybindings',+ '[$next]',+ ]);if (r.exitCode != 0) throw ServiceException('${r.stderr}'.trim());}}diff --git a/ui/linux/runner/my_application.cc b/ui/linux/runner/my_application.ccindex f3360b5..870ed20 100644--- a/ui/linux/runner/my_application.cc+++ b/ui/linux/runner/my_application.cc@@ -9,6 +9,7 @@struct _MyApplication {GtkApplication parent_instance;+ FlMethodChannel* lifecycle_channel;char** dart_entrypoint_arguments;GtkWindow* window; // 已经打开的窗口:再次启动时把它调到前面,而不是再开一个};@@ -39,6 +40,25 @@ static void first_frame_cb(MyApplication* self, FlView* view) {gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));}+static gboolean close_window(GtkWidget*, GdkEvent*, gpointer data) {+ auto* self = MY_APPLICATION(data);+ if (self->lifecycle_channel != nullptr) {+ fl_method_channel_invoke_method(self->lifecycle_channel, "closeRequested", nullptr,+ nullptr, nullptr, nullptr);+ }+ return TRUE;+}++static void lifecycle_method(FlMethodChannel*, FlMethodCall* call, gpointer data) {+ auto* self = MY_APPLICATION(data);+ if (g_strcmp0(fl_method_call_get_name(call), "hideWindow") == 0) {+ gtk_widget_hide(GTK_WIDGET(self->window));+ fl_method_call_respond_success(call, nullptr, nullptr);+ } else {+ fl_method_call_respond_not_implemented(call, nullptr);+ }+}+// Implements GApplication::activate.static void my_application_activate(GApplication* application) {MyApplication* self = MY_APPLICATION(application);@@ -104,6 +124,12 @@ static void my_application_activate(GApplication* application) {gtk_widget_realize(GTK_WIDGET(view));fl_register_plugins(FL_PLUGIN_REGISTRY(view));+ g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new();+ self->lifecycle_channel = fl_method_channel_new(+ fl_engine_get_binary_messenger(fl_view_get_engine(view)),+ "com.pasteferry.app/lifecycle", FL_METHOD_CODEC(codec));+ fl_method_channel_set_method_call_handler(self->lifecycle_channel, lifecycle_method, self, nullptr);+ g_signal_connect(window, "delete-event", G_CALLBACK(close_window), self);gtk_widget_grab_focus(GTK_WIDGET(view));}@@ -150,6 +176,7 @@ static void my_application_shutdown(GApplication* application) {// Implements GObject::dispose.static void my_application_dispose(GObject* object) {MyApplication* self = MY_APPLICATION(object);+ g_clear_object(&self->lifecycle_channel);g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);G_OBJECT_CLASS(my_application_parent_class)->dispose(object);}diff --git a/ui/macos/Runner/AppDelegate.swift b/ui/macos/Runner/AppDelegate.swiftindex b3c1761..4029575 100644--- a/ui/macos/Runner/AppDelegate.swift+++ b/ui/macos/Runner/AppDelegate.swift@@ -3,7 +3,24 @@ import FlutterMacOS@mainclass AppDelegate: FlutterAppDelegate {+ var lifecycleChannel: FlutterMethodChannel?+override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {+ return false+ }++ override func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {+ guard let channel = lifecycleChannel else { return .terminateNow }+ channel.invokeMethod("quitRequested", arguments: nil) { _ in+ // A cancelled transfer prompt or a shutdown error keeps the app running.+ // Successful shutdown exits the process after both helpers have stopped.+ NSApp.reply(toApplicationShouldTerminate: false)+ }+ return .terminateLater+ }++ override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {+ mainFlutterWindow?.makeKeyAndOrderFront(nil)return true}diff --git a/ui/macos/Runner/MainFlutterWindow.swift b/ui/macos/Runner/MainFlutterWindow.swiftindex 1dd9cd6..d73c0c9 100644--- a/ui/macos/Runner/MainFlutterWindow.swift+++ b/ui/macos/Runner/MainFlutterWindow.swift@@ -1,7 +1,14 @@import Cocoaimport FlutterMacOS-class MainFlutterWindow: NSWindow {+class MainFlutterWindow: NSWindow, NSWindowDelegate {+ private var lifecycleChannel: FlutterMethodChannel?++ func windowShouldClose(_ sender: NSWindow) -> Bool {+ lifecycleChannel?.invokeMethod("closeRequested", arguments: nil)+ return false+ }+override func awakeFromNib() {let flutterViewController = FlutterViewController()self.contentViewController = flutterViewController@@ -20,6 +27,19 @@ class MainFlutterWindow: NSWindow {RegisterGeneratedPlugins(registry: flutterViewController)+ let channel = FlutterMethodChannel(name: "com.pasteferry.app/lifecycle",+ binaryMessenger: flutterViewController.engine.binaryMessenger)+ lifecycleChannel = channel+ (NSApp.delegate as? AppDelegate)?.lifecycleChannel = channel+ channel.setMethodCallHandler { [weak self] call, result in+ if call.method == "hideWindow" {+ self?.orderOut(nil)+ result(nil)+ } else {+ result(FlutterMethodNotImplemented)+ }+ }super.awakeFromNib()+ self.delegate = self}}diff --git a/ui/test/macos_service_lifecycle_test.dart b/ui/test/macos_service_lifecycle_test.dartnew file mode 100644index 0000000..048199a--- /dev/null+++ b/ui/test/macos_service_lifecycle_test.dart@@ -0,0 +1,52 @@+import 'dart:io';+import 'package:flutter_test/flutter_test.dart';+import 'package:pasteferry_ui/background_service.dart';++void main() {+ test(+ 'launchd: disabling login keeps this session alive; quit stays stopped; reopening restarts',+ () async {+ final dir = await Directory.systemTemp.createTemp('pasteferry-launchd-');+ final exe = '${dir.path}/PasteFerry.app/Contents/MacOS/PasteFerry';+ final service = MacBackgroundService(+ home: dir.path,+ executable: exe,+ serviceLabel: 'com.pasteferry.lifecycle-test.$pid',+ );+ final binary = File(service.helperBinary);+ await binary.parent.create(recursive: true);+ await binary.writeAsString(+ '#!/bin/sh\ntrap "exit 0" TERM INT\nwhile :; do sleep 1; done\n',+ );+ await Process.run('chmod', ['+x', binary.path]);+ addTearDown(() async {+ await service.uninstall();+ await dir.delete(recursive: true);+ });+ Future<void> waitRunning() async {+ for (var i = 0; i < 40; i++) {+ if (await service.state() == ServiceState.running) return;+ await Future<void>.delayed(const Duration(milliseconds: 100));+ }+ fail('launchd job did not start');+ }++ await service.install();+ await waitRunning();+ expect(await service.launchAtLogin(), isFalse);+ await service.setLaunchAtLogin(true);+ await service.setLaunchAtLogin(false);+ expect(await service.state(), ServiceState.running);+ await service.setLaunchAtLogin(true);+ await service.stop();+ expect(await service.launchAtLogin(), isTrue);+ expect(await service.state(), ServiceState.stopped);+ await Future<void>.delayed(const Duration(seconds: 2));+ expect(await service.state(), ServiceState.stopped);+ await service.install();+ await waitRunning();+ expect(await service.launchAtLogin(), isTrue);+ },+ skip: !Platform.isMacOS,+ );+}diff --git a/ui/test/quit_application_test.dart b/ui/test/quit_application_test.dartnew file mode 100644index 0000000..b61c236--- /dev/null+++ b/ui/test/quit_application_test.dart@@ -0,0 +1,47 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:pasteferry_ui/app_state.dart';+import 'package:pasteferry_ui/background_service.dart';+import 'package:pasteferry_ui/quick_paste_service.dart';++class _Service implements BackgroundService {+ _Service(this.events);+ final List<String> events;+ @override+ bool get available => true;+ @override+ Future<void> stop() async => events.add('daemon stopped');+ @override+ dynamic noSuchMethod(Invocation invocation) =>+ throw StateError('Unexpected: $invocation');+}++class _Picker implements QuickPasteService {+ _Picker(this.events);+ final List<String> events;+ @override+ bool get available => true;+ @override+ Future<void> stop() async => events.add('picker stopped');+ @override+ dynamic noSuchMethod(Invocation invocation) =>+ throw StateError('Unexpected: $invocation');+}++void main() {+ test(+ 'quit stops both helpers without removing or changing login preferences',+ () async {+ final events = <String>[];+ final state = AppState(+ service: _Service(events),+ quickPasteService: _Picker(events),+ );+ addTearDown(state.dispose);+ await state.quitApplication();+ expect(events, ['picker stopped', 'daemon stopped']);+ // Pending retry callbacks and subsequent connections must not restart helpers.+ await state.connect();+ expect(events, ['picker stopped', 'daemon stopped']);+ },+ );+}diff --git a/ui/test/startup_settings_test.dart b/ui/test/startup_settings_test.dartnew file mode 100644index 0000000..3a3a9c1--- /dev/null+++ b/ui/test/startup_settings_test.dart@@ -0,0 +1,57 @@+import 'dart:io';+import 'package:flutter_test/flutter_test.dart';+import 'package:pasteferry_ui/background_service.dart';+import 'package:pasteferry_ui/background_service_linux.dart';+import 'package:pasteferry_ui/quick_paste_service.dart';++void main() {+ test(+ 'Mac login preference changes without stopping the runtime job',+ () async {+ final dir = await Directory.systemTemp.createTemp('pasteferry-startup-');+ addTearDown(() => dir.delete(recursive: true));+ final service = MacBackgroundService(+ home: dir.path,+ executable: '/Applications/PasteFerry.app/Contents/MacOS/PasteFerry',+ );+ final picker = MacQuickPasteService(+ home: dir.path,+ executable: '/Applications/PasteFerry.app/Contents/MacOS/PasteFerry',+ );+ final runtime = File(service.runtimePath);+ await runtime.parent.create(recursive: true);+ await runtime.writeAsString('running-job');+ expect(await service.launchAtLogin(), isFalse);+ await service.setLaunchAtLogin(true);+ await picker.setLaunchAtLogin(true);+ expect(await service.launchAtLogin(), isTrue);+ expect(await File(picker.plistPath).exists(), isTrue);+ await service.setLaunchAtLogin(false);+ await picker.setLaunchAtLogin(false);+ expect(await service.launchAtLogin(), isFalse);+ expect(await File(picker.plistPath).exists(), isFalse);+ expect(await runtime.readAsString(), 'running-job');+ },+ );++ test(+ 'Linux login preference changes without launching or stopping a process',+ () async {+ final dir = await Directory.systemTemp.createTemp('pasteferry-startup-');+ addTearDown(() => dir.delete(recursive: true));+ final service = LinuxBackgroundService(+ executable: '/opt/PasteFerry/pasteferry',+ environment: {'HOME': dir.path},+ );+ expect(await service.launchAtLogin(), isFalse);+ await service.setLaunchAtLogin(true);+ expect(await service.launchAtLogin(), isTrue);+ expect(+ await File(service.autostartPath).readAsString(),+ contains('pasteferryd'),+ );+ await service.setLaunchAtLogin(false);+ expect(await service.launchAtLogin(), isFalse);+ },+ );+}diff --git a/ui/test/sync_controls_test.dart b/ui/test/sync_controls_test.dartnew file mode 100644index 0000000..8054a1c--- /dev/null+++ b/ui/test/sync_controls_test.dart@@ -0,0 +1,87 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:flutter/widgets.dart';+import 'package:pasteferry_ui/app_state.dart';+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';+import 'package:pasteferry_ui/main.dart';+import 'package:pasteferry_ui/widgets/common.dart';++class _State extends AppState {+ @override+ Future<void> updateConfig(Config next) async {+ debugSeed(status: status!, config: next, self: self!, peers: peers);+ }+}++void main() {+ testWidgets('sync defaults and switches preserve independent settings', (+ tester,+ ) async {+ final state = _State()+ ..debugSeed(+ status: Status(),+ config: Config(),+ self: Device(id: 'self'),+ );+ await tester.pumpWidget(PasteFerryApp(state: state));+ await tester.tap(find.text('设置').first);+ await tester.pumpAndSettle();+ Future<void> toggle(String title) async {+ await tester.scrollUntilVisible(+ find.text(title),+ 250,+ scrollable: find.descendant(of: find.byType(ListView).last, matching: find.byType(Scrollable)).first,+ );+ final row = find.ancestor(+ of: find.text(title).first,+ matching: find.byType(SettingRow),+ );+ await tester.ensureVisible(row);+ await tester.tap(+ find.descendant(of: row, matching: find.byType(SmallSwitch)),+ );+ await tester.pumpAndSettle();+ }++ expect(state.config!.syncBacklog, isFalse);+ await toggle('实时同步剪贴板');+ expect(state.config!.realtimeSyncDisabled, isTrue);+ expect(+ state.config!.syncText,+ isFalse,+ ); // Unrelated content settings stay intact.+ await toggle('重连后补发离线内容');+ expect(state.config!.syncBacklog, isTrue);+ expect(state.config!.realtimeSyncDisabled, isTrue);+ expect(state.config!.launchAtLogin, isFalse);+ });++ testWidgets(+ 'a device can pause sync without unpairing or changing other devices',+ (tester) async {+ final state = _State()+ ..debugSeed(+ status: Status(),+ config: Config(),+ self: Device(id: 'self'),+ peers: [+ Device(id: 'home', name: 'Home'),+ Device(id: 'office', name: 'Office'),+ ],+ );+ await tester.pumpWidget(PasteFerryApp(state: state));+ await tester.tap(find.text('设备').first);+ await tester.pumpAndSettle();+ await tester.tap(+ find.descendant(+ of: find.byTooltip('与这台电脑实时同步').first,+ matching: find.byType(SmallSwitch),+ ),+ );+ await tester.pumpAndSettle();+ expect(state.config!.syncDisabledPeers, ['home']);+ expect(state.peers.length, 2);+ expect(find.text('剪贴板同步已暂停'), findsOneWidget);+ expect(tester.takeException(), isNull);+ },+ );+}diff --git a/ui/tool/screenshots/screenshots_test.dart b/ui/tool/screenshots/screenshots_test.dartindex 330093d..4cbd420 100644--- a/ui/tool/screenshots/screenshots_test.dart+++ b/ui/tool/screenshots/screenshots_test.dart@@ -185,7 +185,7 @@ AppState _demo({LinkState link = LinkState.online,serviceState: service,pendingPairing: pending,status: Status(- version: '2.5.0',+ version: '2.5.3',deviceName: 'MacBook Pro',signalingConnected: link == LinkState.online && server.isNotEmpty,serverConfigured: server.isNotEmpty,diff --git a/ui/windows/runner/flutter_window.cpp b/ui/windows/runner/flutter_window.cppindex 07ff9fe..c60fbeb 100644--- a/ui/windows/runner/flutter_window.cpp+++ b/ui/windows/runner/flutter_window.cpp@@ -1,6 +1,7 @@#include "flutter_window.h"#include <flutter_windows.h>+#include <flutter/standard_method_codec.h>#include <optional>@@ -67,6 +68,17 @@ bool FlutterWindow::OnCreate() {return false;}RegisterPlugins(flutter_controller_->engine());+ lifecycle_channel_ = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(+ flutter_controller_->engine()->messenger(), "com.pasteferry.app/lifecycle",+ &flutter::StandardMethodCodec::GetInstance());+ lifecycle_channel_->SetMethodCallHandler([this](const auto& call, auto result) {+ if (call.method_name() == "hideWindow") {+ ::ShowWindow(GetHandle(), SW_HIDE);+ result->Success();+ } else {+ result->NotImplemented();+ }+ });SetChildContent(flutter_controller_->view()->GetNativeWindow());flutter_controller_->engine()->SetNextFrameCallback([this, maximized]() {@@ -85,6 +97,7 @@ bool FlutterWindow::OnCreate() {}void FlutterWindow::OnDestroy() {+ lifecycle_channel_ = nullptr;if (flutter_controller_) {flutter_controller_ = nullptr;}@@ -96,6 +109,15 @@ LRESULTFlutterWindow::MessageHandler(HWND hwnd, UINT const message,WPARAM const wparam,LPARAM const lparam) noexcept {+ if (lifecycle_channel_ && (message == WM_CLOSE || message == WM_APP + 87)) {+ SavePlacement(hwnd);+ if (message == WM_APP + 87) {+ ::ShowWindow(hwnd, SW_SHOW);+ ::SetForegroundWindow(hwnd);+ }+ lifecycle_channel_->InvokeMethod(message == WM_CLOSE ? "closeRequested" : "quitRequested", nullptr);+ return 0;+ }// Give Flutter, including plugins, an opportunity to handle window messages.if (flutter_controller_) {std::optional<LRESULT> result =diff --git a/ui/windows/runner/flutter_window.h b/ui/windows/runner/flutter_window.hindex 6da0652..819df3d 100644--- a/ui/windows/runner/flutter_window.h+++ b/ui/windows/runner/flutter_window.h@@ -2,6 +2,8 @@#define RUNNER_FLUTTER_WINDOW_H_#include <flutter/dart_project.h>+#include <flutter/method_channel.h>+#include <flutter/encodable_value.h>#include <flutter/flutter_view_controller.h>#include <memory>@@ -23,6 +25,8 @@ class FlutterWindow : public Win32Window {LPARAM const lparam) noexcept override;private:+ std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> lifecycle_channel_;+// The project to run.flutter::DartProject project_;diff --git a/ui/windows/runner/main.cpp b/ui/windows/runner/main.cppindex 1d9e80a..d265a62 100644--- a/ui/windows/runner/main.cpp+++ b/ui/windows/runner/main.cpp@@ -55,6 +55,7 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,if (::GetLastError() == ERROR_ALREADY_EXISTS) {HWND existing = ::FindWindowW(L"FLUTTER_RUNNER_WIN32_WINDOW", L"PasteFerry");if (existing) {+ ::ShowWindow(existing, SW_SHOW);if (::IsIconic(existing)) {::ShowWindow(existing, SW_RESTORE);}