Skip to content

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.

feat(ui): add favorites page, link filter, hover details and quick paste

baiyuze21e3993baafb
diff --git a/ui/lib/app_state.dart b/ui/lib/app_state.dart
index d36334e..9d96808 100644
--- a/ui/lib/app_state.dart
+++ b/ui/lib/app_state.dart
@@ -7,8 +7,10 @@ import 'package:grpc/grpc.dart';
import 'background_service.dart';
import 'daemon_client.dart';
import 'i18n.dart';
+import 'quick_paste_service.dart';
import 'gen/pasteferry/v1/daemon.pb.dart';
import 'gen/pasteferry/v1/daemon.pbgrpc.dart' show DaemonServiceClient;
+import 'widgets/record_hover.dart' show RecordDetails;
/// daemon 连接的生命周期状态。
enum LinkState { connecting, online, offline }
@@ -30,12 +32,16 @@ enum PairingFailure {
///
/// 所有与 daemon 的交互都经过这里:页面只读状态、调方法,不直接碰 gRPC。
/// 这样断线重连、事件合并这些琐事集中在一处,页面代码保持干净。
-class AppState extends ChangeNotifier {
- AppState({BackgroundService? service})
- : service = service ?? BackgroundService();
+class AppState extends ChangeNotifier implements RecordDetails {
+ AppState({BackgroundService? service, QuickPasteService? quickPasteService})
+ : service = service ?? BackgroundService(),
+ quickPasteService = quickPasteService ?? QuickPasteService();
final BackgroundService service;
+ /// Mac 上快捷粘贴窗口的 LaunchAgent,见 quick_paste_service.dart
+ final QuickPasteService quickPasteService;
+
DaemonConnection? _conn;
StreamSubscription<Event>? _events;
Timer? _retry;
@@ -48,6 +54,15 @@ class AppState extends ChangeNotifier {
List<Device> _peers = const [];
final List<ClipRecord> _records = [];
+ /// 收藏,按收藏时间倒序。和复制记录是两份,见 design/quick-paste-and-favorites.md 第 3 节
+ final List<ClipRecord> _favorites = [];
+
+ /// 悬停提示框要显示的完整内容,按记录 ID 缓存:内容不会变
+ final Map<String, ClipDetail> _details = {};
+
+ /// 快捷粘贴窗口的状态,由后台服务转来;没连上时为 null
+ QuickPasteStatus? _quickPaste;
+
/// 正在传输的记录的进度(0–1),只在界面上展示,传完即移除。
final Map<String, double> _progress = {};
final Map<String, ClipboardWriteResult> _clipboardResults = {};
@@ -55,12 +70,18 @@ class AppState extends ChangeNotifier {
NotificationStatus? get notificationStatus => _notificationStatus;
ClipboardWriteResult? clipboardResultOf(String id) => _clipboardResults[id];
- /// 复制记录的搜索:搜索词,以及后台服务返回的结果(还没出结果时为 null)。
- /// 界面只加载最新的 200 条,更早的记录只有后台服务能搜到,所以不在界面里筛选。
- String _query = '';
- List<ClipRecord>? _searchResults;
- Timer? _searchTimer;
- int _searchSeq = 0; // 只采用最后一次搜索的结果,先发出的请求可能后返回
+ /// 复制记录与收藏各自的搜索。界面只加载最新的 200 条复制记录,更早的只有后台服务能搜到,
+ /// 所以不在界面里筛选。
+ late final _historySearch = _RecordSearch(
+ notify: notifyListeners,
+ request: (q) => requestSearch(q),
+ local: () => _records,
+ );
+ late final _favoriteSearch = _RecordSearch(
+ notify: notifyListeners,
+ request: (q) => requestFavoriteSearch(q),
+ local: () => _favorites,
+ );
/// 待用户核对指纹的配对请求。非空时界面弹出确认。
Device? _pendingPairing;
@@ -77,14 +98,24 @@ class AppState extends ChangeNotifier {
Device? get self => _self;
List<Device> get peers => List.unmodifiable(_peers);
List<ClipRecord> get records => List.unmodifiable(_records);
+ List<ClipRecord> get favorites => List.unmodifiable(_favorites);
+
+ /// 全部收藏的大小之和。硬链接、写时复制保存的副本实际占用更少,界面上写「最多」
+ int get favoritesBytes => _favorites.fold(0, (n, r) => n + r.totalSize.toInt());
+
+ QuickPasteStatus? get quickPaste => _quickPaste;
/// 正在搜索复制记录(搜索词不是空白)。
- bool get searching => _query.trim().isNotEmpty;
- String get searchQuery => _query.trim();
+ bool get searching => _historySearch.active;
+ String get searchQuery => _historySearch.query.trim();
/// 搜到的记录,按时间倒序;没在搜索、或这次搜索还没出结果时为 null。
- List<ClipRecord>? get searchResults =>
- _searchResults == null ? null : List.unmodifiable(_searchResults!);
+ List<ClipRecord>? get searchResults => _historySearch.resultsView;
+
+ /// 收藏页的搜索,与复制记录的分开。
+ bool get searchingFavorites => _favoriteSearch.active;
+ String get favoriteQuery => _favoriteSearch.query.trim();
+ List<ClipRecord>? get favoriteResults => _favoriteSearch.resultsView;
/// 传输进度;总量未知或尚未开始时为 null。
double? progressOf(String clipId) => _progress[clipId];
@@ -162,7 +193,8 @@ class AppState extends ChangeNotifier {
@override
void dispose() {
_retry?.cancel();
- _searchTimer?.cancel();
+ _historySearch.dispose();
+ _favoriteSearch.dispose();
_events?.cancel();
_conn?.close();
super.dispose();
@@ -184,6 +216,7 @@ class AppState extends ChangeNotifier {
conn.client.listHistory(ListHistoryRequest(limit: 200)),
conn.client.getConfig(Empty()),
conn.client.getStatus(Empty()),
+ conn.client.listHistory(ListHistoryRequest(limit: 500, favorites: true)),
]);
_records
@@ -191,6 +224,11 @@ class AppState extends ChangeNotifier {
..addAll((results[0] as ListHistoryResponse).records);
_config = results[1] as Config;
_status = results[2] as Status;
+ // 旧版后台服务不认识 favorites,会把复制记录原样返回:只收下真的收藏
+ _favorites
+ ..clear()
+ ..addAll((results[3] as ListHistoryResponse).records.where((r) => r.favorite));
+ await _loadQuickPasteStatus();
await _loadDevices();
await refreshNotificationStatus();
@@ -207,7 +245,8 @@ class AppState extends ChangeNotifier {
_serviceState = null;
_setLink(LinkState.online, null);
_ensureServiceCurrent();
- if (searching) _scheduleSearch(Duration.zero);
+ _historySearch.schedule(Duration.zero);
+ _favoriteSearch.schedule(Duration.zero);
} on DaemonNotRunning {
await _refreshServiceState();
_scheduleRetry(appL10n.linkServiceNotRunning);
@@ -262,6 +301,28 @@ class AppState extends ChangeNotifier {
} catch (_) {
// 核对失败不影响使用:旧进程仍在正常工作
}
+ await _syncQuickPaste();
+ }
+
+ /// Mac 上按设置登记或撤下快捷粘贴窗口的 LaunchAgent;App 更新后还在跑旧版的,按新的程序重新拉起。
+ /// Windows、Linux 上快捷窗口由后台服务照看,这里什么都不做。
+ Future<void> _syncQuickPaste() async {
+ final qp = quickPasteService;
+ if (!qp.available) return;
+ try {
+ // 快捷窗口跟着后台服务走:后台服务没登记成登录项(开发时手动跑的、测试用的)就不登记它
+ if (await service.state() != ServiceState.running) return;
+ if (_config?.quickPasteDisabled ?? false) {
+ await qp.uninstall();
+ } else if (!await qp.installed()) {
+ await qp.install();
+ } else {
+ final v = _quickPaste?.version ?? '';
+ if (appVersion != 'dev' && v.isNotEmpty && v != appVersion) await qp.restart();
+ }
+ } catch (_) {
+ // 登记失败不影响主界面,设置页会显示快捷窗口没在运行
+ }
}
/// 截图与界面测试用:直接填入数据,不连接后台服务。
@@ -272,9 +333,11 @@ class AppState extends ChangeNotifier {
required Device self,
List<Device> peers = const [],
List<ClipRecord> records = const [],
+ List<ClipRecord> favorites = const [],
Device? pendingPairing,
LinkState link = LinkState.online,
ServiceState? serviceState,
+ QuickPasteStatus? quickPaste,
}) {
_status = status;
_config = config;
@@ -283,6 +346,10 @@ class AppState extends ChangeNotifier {
_records
..clear()
..addAll(records);
+ _favorites
+ ..clear()
+ ..addAll(favorites);
+ _quickPaste = quickPaste;
_pendingPairing = pendingPairing;
_serviceState = serviceState;
_link = link;
@@ -296,6 +363,7 @@ class AppState extends ChangeNotifier {
await service.install();
await _refreshServiceState();
await connect();
+ await _syncQuickPaste();
}
Future<void> restartService() async {
@@ -303,9 +371,10 @@ class AppState extends ChangeNotifier {
await connect();
}
- /// 停用后台服务:关闭同步并取消开机自启。
+ /// 停用后台服务:关闭同步并取消开机自启。快捷窗口离了后台服务没法用,一起撤下,重新启用时再登记。
Future<void> disableService() async {
_retry?.cancel();
+ if (quickPasteService.available) await quickPasteService.uninstall();
await service.uninstall();
await _refreshServiceState();
_scheduleRetry(appL10n.linkServiceDisabled);
@@ -349,18 +418,32 @@ class AppState extends ChangeNotifier {
case Event_Payload.clipAdded:
_upsert(ev.clipAdded);
// 新记录该不该出现在搜索结果里,只有后台服务知道
- if (!_patchSearch(ev.clipAdded)) {
- _scheduleSearch(const Duration(milliseconds: 300));
+ final search = ev.clipAdded.favorite ? _favoriteSearch : _historySearch;
+ if (!search.patch(ev.clipAdded)) {
+ search.schedule(const Duration(milliseconds: 300));
}
+ // 取消收藏后同一条记录换到了复制记录里
+ (ev.clipAdded.favorite ? _historySearch : _favoriteSearch).remove(ev.clipAdded.id);
case Event_Payload.clipUpdated:
_upsert(ev.clipUpdated);
- _patchSearch(ev.clipUpdated);
+ _historySearch.patch(ev.clipUpdated);
+ _favoriteSearch.patch(ev.clipUpdated);
case Event_Payload.clipRemoved:
_records.removeWhere((r) => r.id == ev.clipRemoved);
+ _favorites.removeWhere((r) => r.id == ev.clipRemoved);
_clipboardResults.remove(ev.clipRemoved);
- _searchResults?.removeWhere((r) => r.id == ev.clipRemoved);
+ _details.remove(ev.clipRemoved);
+ _historySearch.remove(ev.clipRemoved);
+ _favoriteSearch.remove(ev.clipRemoved);
+
+ case Event_Payload.configChanged:
+ // 别处(快捷窗口、另一个界面窗口)改了设置
+ _config = ev.configChanged;
+
+ case Event_Payload.quickPasteChanged:
+ _quickPaste = ev.quickPasteChanged;
case Event_Payload.clipboardWritten:
_clipboardResults[ev.clipboardWritten.clipId] = ev.clipboardWritten;
@@ -382,11 +465,27 @@ class AppState extends ChangeNotifier {
void _upsert(ClipRecord r) {
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);
+ if (i >= 0) {
+ _favorites[i] = r;
+ } else {
+ _favorites.add(r);
+ }
+ // 再收藏一次同样的内容会把它挪到最上面
+ _favorites.sort((a, b) => b.favoritedAtUnix.compareTo(a.favoritedAtUnix));
+ return;
+ }
+ // 取消收藏:同一条记录从收藏挪回复制记录
+ _favorites.removeWhere((x) => x.id == r.id);
final i = _records.indexWhere((x) => x.id == r.id);
if (i >= 0) {
_records[i] = r;
} else {
- _records.insert(0, r);
+ // 按复制时间插到该在的位置:新复制的、刚取消收藏的都在最上面
+ final at = _records.indexWhere((x) => x.createdAtUnix < r.createdAtUnix);
+ _records.insert(at < 0 ? _records.length : at, r);
if (_records.length > 500) _records.removeLast();
}
// 传完(或失败)了就不再显示进度
@@ -402,7 +501,7 @@ class AppState extends ChangeNotifier {
if (r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY) {
// 用户点了「拉取到本机」,开始传了
_records[i] = r.deepCopy()..status = ClipStatus.CLIP_STATUS_FETCHING;
- _patchSearch(_records[i]);
+ _historySearch.patch(_records[i]);
} else if (r.status != ClipStatus.CLIP_STATUS_FETCHING) {
return; // 已经传完的记录,迟到的进度事件不能把它拉回「接收中」
}
@@ -522,9 +621,11 @@ class AppState extends ChangeNotifier {
Future<void> updateConfig(Config next) async {
final wasOfficial = officialEnabled;
+ final quickPasteWasDisabled = _config?.quickPasteDisabled;
_config = await _client.updateConfig(next);
if (!wasOfficial && officialEnabled) _officialNavigationSerial++;
notifyListeners();
+ if (_config!.quickPasteDisabled != quickPasteWasDisabled) await _syncQuickPaste();
}
// ─────────────────────────── 更新 ───────────────────────────
@@ -580,69 +681,80 @@ class AppState extends ChangeNotifier {
DeleteHistoryRequest(ids: ids ?? const [], all: all),
);
if (all) {
+ // 清空只清复制记录,收藏不受影响
_records.clear();
- _searchResults?.clear();
+ _historySearch.clear();
} else if (ids != null) {
_records.removeWhere((r) => ids.contains(r.id));
- _searchResults?.removeWhere((r) => ids.contains(r.id));
+ ids.forEach(_historySearch.remove);
}
notifyListeners();
}
- // ─────────────────────────── 搜索复制记录 ───────────────────────────
+ // ─────────────────────────── 收藏 ───────────────────────────
- /// 输入搜索词。停顿一下再向后台服务查询,不必每敲一个字就查一次;空白表示不搜索。
- /// [notify] 为 false 用于页面销毁时清掉搜索:那时界面树已锁定,不能再通知重建。
- void search(String query, {bool notify = true}) {
- _query = query;
- _searchTimer?.cancel();
- if (!searching) {
- _searchSeq++;
- _searchResults = null;
- if (notify) notifyListeners();
- return;
- }
- _scheduleSearch(const Duration(milliseconds: 200));
+ /// 收藏(另存一份)或取消收藏(放回复制记录的最上面)。返回收藏后的收藏,或取消后放回的那一条。
+ /// 取消收藏时 [clipId] 是收藏或它的原记录都可以。
+ Future<ClipRecord> setFavorite(String clipId, bool favorite) async {
+ final r = await _client.setFavorite(
+ SetFavoriteRequest(clipId: clipId, favorite: favorite),
+ // 整份复制大文件时后台服务先返回「正在保存」,不会等太久
+ options: CallOptions(timeout: const Duration(seconds: 30)),
+ );
+ _upsert(r);
+ (r.favorite ? _historySearch : _favoriteSearch).remove(r.id);
+ notifyListeners();
+ return r;
}
- void _scheduleSearch(Duration delay) {
- if (!searching) return;
- _searchTimer?.cancel();
- _searchTimer = Timer(delay, _runSearch);
+ /// 悬停提示框要显示的完整内容。
+ @override
+ Future<ClipDetail> clipDetail(String clipId) async {
+ final cached = _details[clipId];
+ if (cached != null) return cached;
+ final d = await requestClipDetail(clipId);
+ _details[clipId] = d;
+ return d;
}
- Future<void> _runSearch() async {
- final query = searchQuery;
- final seq = ++_searchSeq;
- List<ClipRecord> found;
+ @protected
+ Future<ClipDetail> requestClipDetail(String clipId) =>
+ _client.getClipDetail(GetClipDetailRequest(clipId: clipId));
+
+ // ─────────────────────────── 快捷粘贴窗口 ───────────────────────────
+
+ Future<void> _loadQuickPasteStatus() async {
+ final conn = _conn;
+ if (conn == null) return;
try {
- final r = await requestSearch(query);
- // 旧版后台服务不认识搜索词,会原样返回全部记录:退回到只在已加载的记录里找
- found = r.searched
- ? List.of(r.records)
- : _records.where((x) => matchesSearch(x, query)).toList();
- } catch (_) {
- found = _records.where((x) => matchesSearch(x, query)).toList();
+ _quickPaste = await conn.client.getQuickPasteStatus(Empty());
+ } on GrpcError {
+ _quickPaste = null; // 旧版后台服务没有快捷窗口
}
- if (seq != _searchSeq || query != searchQuery) return;
- _searchResults = found;
- notifyListeners();
}
+ /// 转给快捷窗口的命令:request_permission、suspend_hotkey、resume_hotkey、show。
+ Future<void> sendQuickPasteCommand(String command) =>
+ _client.sendQuickPasteCommand(QuickPasteCommand(command: command));
+
+ // ─────────────────────────── 搜索 ───────────────────────────
+
+ /// 输入搜索词。停顿一下再向后台服务查询,不必每敲一个字就查一次;空白表示不搜索。
+ /// [notify] 为 false 用于页面销毁时清掉搜索:那时界面树已锁定,不能再通知重建。
+ 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);
+
/// 向后台服务搜索复制记录。界面测试与截图里由子类给出演示结果。
@protected
Future<ListHistoryResponse> requestSearch(String query) =>
_client.listHistory(ListHistoryRequest(limit: 200, query: query));
- /// 搜索结果里的同一条记录跟着更新状态(拉取进度、失败等),预览保留搜索给的那一段。
- /// 返回这条记录在不在结果里。
- bool _patchSearch(ClipRecord r) {
- final results = _searchResults;
- final i = results?.indexWhere((x) => x.id == r.id) ?? -1;
- if (i < 0) return false;
- results![i] = r.deepCopy()..textPreview = results[i].textPreview;
- return true;
- }
+ /// 向后台服务搜索收藏。
+ @protected
+ Future<ListHistoryResponse> requestFavoriteSearch(String query) =>
+ _client.listHistory(ListHistoryRequest(limit: 200, query: query, favorites: true));
Future<void> refreshNotificationStatus() async {
final conn = _conn;
@@ -674,6 +786,7 @@ class AppState extends ChangeNotifier {
/// 一条记录里第 [index] 张图片:本机路径、文件名,以及能预览的图片总数。
/// HEIC 这类格式由后台服务先转换,大图可能要一两秒,超时放宽一些。
+ @override
Future<GetImagePreviewResponse> imagePreview(
String clipId, {
int index = 0,
@@ -714,6 +827,75 @@ class AppState extends ChangeNotifier {
}
}
+/// 一组记录(复制记录或收藏)的搜索:搜索词、后台服务返回的结果,以及「只采用最后一次」的计数。
+class _RecordSearch {
+ _RecordSearch({required this.notify, required this.request, required this.local});
+
+ final VoidCallback notify;
+ final Future<ListHistoryResponse> Function(String query) request;
+
+ /// 已加载的记录:后台服务不支持搜索时在这里面找
+ final List<ClipRecord> Function() local;
+
+ String query = '';
+ List<ClipRecord>? _results;
+ Timer? _timer;
+ int _seq = 0; // 只采用最后一次搜索的结果,先发出的请求可能后返回
+
+ bool get active => query.trim().isNotEmpty;
+ List<ClipRecord>? get resultsView => _results == null ? null : List.unmodifiable(_results!);
+
+ void set(String q, {bool notify = true}) {
+ query = q;
+ _timer?.cancel();
+ if (!active) {
+ _seq++;
+ _results = null;
+ if (notify) this.notify();
+ return;
+ }
+ schedule(const Duration(milliseconds: 200));
+ }
+
+ void schedule(Duration delay) {
+ if (!active) return;
+ _timer?.cancel();
+ _timer = Timer(delay, _run);
+ }
+
+ Future<void> _run() async {
+ final q = query.trim();
+ final seq = ++_seq;
+ List<ClipRecord> found;
+ try {
+ final r = await request(q);
+ // 旧版后台服务不认识搜索词,会原样返回全部记录:退回到只在已加载的记录里找
+ found = r.searched ? List.of(r.records) : local().where((x) => matchesSearch(x, q)).toList();
+ } catch (_) {
+ found = local().where((x) => matchesSearch(x, q)).toList();
+ }
+ if (seq != _seq || q != query.trim()) return;
+ _results = found;
+ notify();
+ }
+
+ /// 结果里的同一条记录跟着更新状态(拉取进度、星标等),预览保留搜索给的那一段。
+ /// 返回这条记录在不在结果里。
+ bool patch(ClipRecord r) {
+ final results = _results;
+ final i = results?.indexWhere((x) => x.id == r.id) ?? -1;
+ if (i < 0) return false;
+ results![i] = r.deepCopy()..textPreview = results[i].textPreview;
+ return true;
+ }
+
+ void remove(String id) => _results?.removeWhere((r) => r.id == id);
+
+ void clear() => _results?.clear();
+
+ void dispose() => _timer?.cancel();
+}
+
/// 在界面已有的信息里判断一条记录是否匹配搜索词:预览片段或文件名包含它,不分大小写。
/// 只在后台服务不支持搜索时用;正常情况下由后台服务按全文搜索。
bool matchesSearch(ClipRecord r, String query) {
diff --git a/ui/lib/hotkey.dart b/ui/lib/hotkey.dart
new file mode 100644
index 0000000..9d7aa6c
--- /dev/null
+++ b/ui/lib/hotkey.dart
@@ -0,0 +1,149 @@
+import 'dart:io';
+
+import 'package:flutter/services.dart';
+
+/// 呼出快捷粘贴窗口的快捷键。写法与后台服务的 config.NormalizeHotkey 相同:
+/// 修饰键在前、按 ctrl、alt、shift、meta 的顺序,最后是一个键,用 + 连起来,全小写,如 "alt+v"。
+/// meta 是 Mac 上的 ⌘、Windows 上的 Win 键、Linux 上的 Super 键。快捷窗口的原生外壳按同样的写法解析。
+class Hotkey {
+ const Hotkey(this.modifiers, this.key);
+
+ /// 修饰键,按 [order] 排好
+ final List<String> modifiers;
+ final String key;
+
+ static const order = ['ctrl', 'alt', 'shift', 'meta'];
+
+ /// 默认的 ⌥V / Alt+V。设置里存空字符串就是它
+ static const fallback = Hotkey(['alt'], 'v');
+
+ static const _aliases = {
+ 'control': 'ctrl', 'option': 'alt', 'opt': 'alt',
+ 'cmd': 'meta', 'command': 'meta', 'win': 'meta', 'super': 'meta',
+ };
+
+ static const _named = {
+ 'space', 'tab', 'enter', 'backspace', 'delete', 'insert', 'home', 'end', 'pageup', 'pagedown',
+ 'up', 'down', 'left', 'right', 'comma', 'period', 'slash', 'semicolon', 'quote',
+ 'bracketleft', 'bracketright', 'backslash', 'minus', 'equal', 'backquote',
+ };
+
+ /// 设置里存的字符串 → 快捷键。空字符串是默认的;写不对的返回 null。
+ static Hotkey? parse(String s) {
+ s = s.trim().replaceAll(' ', '').toLowerCase();
+ if (s.isEmpty) return fallback;
+ final parts = s.split('+');
+ final key = parts.removeLast();
+ final mods = <String>{};
+ for (var p in parts) {
+ p = _aliases[p] ?? p;
+ if (!order.contains(p) || !mods.add(p)) return null;
+ }
+ if (!isValidKey(key)) return null;
+ if (mods.isEmpty && !isFunctionKey(key)) return null;
+ return Hotkey([for (final m in order) if (mods.contains(m)) m], key);
+ }
+
+ static bool isFunctionKey(String k) {
+ final m = RegExp(r'^f([1-9][0-9]?)$').firstMatch(k);
+ if (m == null) return false;
+ final n = int.parse(m.group(1)!);
+ return n >= 1 && n <= 24;
+ }
+
+ static bool isValidKey(String k) => isFunctionKey(k) || _named.contains(k) || RegExp(r'^[a-z0-9]$').hasMatch(k);
+
+ /// 设置里存的写法。等于默认的时候存空字符串,以后默认值变了跟着变
+ String get setting => this == fallback ? '' : canonical;
+
+ String get canonical => [...modifiers, key].join('+');
+
+ /// 显示给用户看的写法:Mac 上 ⌃⌥⇧⌘V,Windows 上 Ctrl+Alt+Shift+Win+V,Linux 上 Win 写成 Super。
+ String display({bool? mac}) {
+ final isMac = mac ?? Platform.isMacOS;
+ if (isMac) {
+ const symbols = {'ctrl': '⌃', 'alt': '⌥', 'shift': '⇧', 'meta': '⌘'};
+ return '${modifiers.map((m) => symbols[m]).join()}${_keyLabel(key, mac: true)}';
+ }
+ final names = {'ctrl': 'Ctrl', 'alt': 'Alt', 'shift': 'Shift', 'meta': Platform.isLinux ? 'Super' : 'Win'};
+ return [...modifiers.map((m) => names[m]!), _keyLabel(key, mac: false)].join('+');
+ }
+
+ static String _keyLabel(String k, {required bool mac}) {
+ const punct = {
+ 'comma': ',', 'period': '.', 'slash': '/', 'semicolon': ';', 'quote': "'", 'bracketleft': '[',
+ 'bracketright': ']', 'backslash': r'\', 'minus': '-', 'equal': '=', 'backquote': '`',
+ 'up': '↑', 'down': '↓', 'left': '←', 'right': '→',
+ };
+ const macNamed = {'enter': '↩', 'tab': '⇥', 'backspace': '⌫', 'delete': '⌦', 'space': 'Space',
+ 'home': '↖', 'end': '↘', 'pageup': '⇞', 'pagedown': '⇟'};
+ const pcNamed = {'enter': 'Enter', 'tab': 'Tab', 'backspace': 'Backspace', 'delete': 'Delete', 'space': 'Space',
+ 'insert': 'Insert', 'home': 'Home', 'end': 'End', 'pageup': 'PageUp', 'pagedown': 'PageDown'};
+ return punct[k] ?? (mac ? macNamed[k] : pcNamed[k]) ?? k.toUpperCase();
+ }
+
+ /// 录制快捷键时,把按下的键换成快捷键。按的是修饰键本身、或者不认识的键时返回 null。
+ /// 不带修饰键的普通键也返回一个结果,由调用方提示「要带上修饰键」。
+ static Hotkey? fromKey(LogicalKeyboardKey logical, PhysicalKeyboardKey physical, Set<String> modifiers) {
+ final key = _keyName(logical) ?? _physicalName(physical);
+ if (key == null) return null;
+ return Hotkey([for (final m in order) if (modifiers.contains(m)) m], key);
+ }
+
+ /// 当前按着的修饰键。
+ static Set<String> pressedModifiers() {
+ final kb = HardwareKeyboard.instance;
+ return {
+ if (kb.isControlPressed) 'ctrl',
+ if (kb.isAltPressed) 'alt',
+ if (kb.isShiftPressed) 'shift',
+ if (kb.isMetaPressed) 'meta',
+ };
+ }
+
+ /// 是不是能当快捷键用(不带修饰键时只能是功能键)。
+ bool get usable => modifiers.isNotEmpty || isFunctionKey(key);
+
+ static final _logicalNames = <LogicalKeyboardKey, String>{
+ LogicalKeyboardKey.space: 'space', LogicalKeyboardKey.tab: 'tab', LogicalKeyboardKey.enter: 'enter',
+ LogicalKeyboardKey.backspace: 'backspace', LogicalKeyboardKey.delete: 'delete',
+ LogicalKeyboardKey.insert: 'insert', LogicalKeyboardKey.home: 'home', LogicalKeyboardKey.end: 'end',
+ LogicalKeyboardKey.pageUp: 'pageup', LogicalKeyboardKey.pageDown: 'pagedown',
+ LogicalKeyboardKey.arrowUp: 'up', LogicalKeyboardKey.arrowDown: 'down',
+ LogicalKeyboardKey.arrowLeft: 'left', LogicalKeyboardKey.arrowRight: 'right',
+ LogicalKeyboardKey.comma: 'comma', LogicalKeyboardKey.period: 'period', LogicalKeyboardKey.slash: 'slash',
+ LogicalKeyboardKey.semicolon: 'semicolon', LogicalKeyboardKey.quote: 'quote',
+ LogicalKeyboardKey.bracketLeft: 'bracketleft', LogicalKeyboardKey.bracketRight: 'bracketright',
+ LogicalKeyboardKey.backslash: 'backslash', LogicalKeyboardKey.minus: 'minus',
+ LogicalKeyboardKey.equal: 'equal', LogicalKeyboardKey.backquote: 'backquote',
+ };
+
+ static String? _keyName(LogicalKeyboardKey k) {
+ final named = _logicalNames[k];
+ if (named != null) return named;
+ final label = k.keyLabel.toLowerCase();
+ if (RegExp(r'^[a-z0-9]$').hasMatch(label)) return label;
+ if (isFunctionKey(label)) return label;
+ return null;
+ }
+
+ /// 按着 ⌥ 时有的布局给出的逻辑键是别的字符(如 √),退回按物理位置认字母与数字(USB HID 键码)。
+ static String? _physicalName(PhysicalKeyboardKey k) {
+ final u = k.usbHidUsage;
+ final a = PhysicalKeyboardKey.keyA.usbHidUsage;
+ if (u >= a && u <= PhysicalKeyboardKey.keyZ.usbHidUsage) return String.fromCharCode(0x61 + u - a);
+ final one = PhysicalKeyboardKey.digit1.usbHidUsage;
+ if (u >= one && u <= PhysicalKeyboardKey.digit9.usbHidUsage) return '${1 + u - one}';
+ if (k == PhysicalKeyboardKey.digit0) return '0';
+ return null;
+ }
+
+ @override
+ bool operator ==(Object other) => other is Hotkey && other.canonical == canonical;
+
+ @override
+ int get hashCode => canonical.hashCode;
+
+ @override
+ String toString() => canonical;
+}
diff --git a/ui/lib/icons.dart b/ui/lib/icons.dart
index b3387df..0fba2ce 100644
--- a/ui/lib/icons.dart
+++ b/ui/lib/icons.dart
@@ -52,4 +52,10 @@ abstract final class AppIcons {
static IconData get chevronRight => _pick(CupertinoIcons.chevron_right, FluentIcons.chevron_right_24_regular);
static IconData get chevronUpDown =>
_pick(CupertinoIcons.chevron_up_chevron_down, FluentIcons.chevron_up_down_24_regular);
+ static IconData get link => _pick(CupertinoIcons.link, FluentIcons.link_24_regular);
+ static IconData get star => _pick(CupertinoIcons.star, FluentIcons.star_24_regular);
+ static IconData get starFill => _pick(CupertinoIcons.star_fill, FluentIcons.star_24_filled);
+ static IconData get keyboard => _pick(CupertinoIcons.keyboard, FluentIcons.keyboard_24_regular);
+ // 回车键:快捷窗口底栏的按键提示里用。字符 ↩ 在 Mac 上会被画成彩色 emoji,所以用图标
+ static IconData get returnKey => _pick(CupertinoIcons.return_icon, FluentIcons.arrow_enter_left_20_regular);
}
diff --git a/ui/lib/l10n/app_en.arb b/ui/lib/l10n/app_en.arb
index 0d39948..f190f98 100644
--- a/ui/lib/l10n/app_en.arb
+++ b/ui/lib/l10n/app_en.arb
@@ -4,6 +4,7 @@
"navHistory": "History",
"navDevices": "Devices",
"navSettings": "Settings",
+ "navFavorites": "Favorites",
"linkConnecting": "Connecting…",
"linkServiceNotRunning": "Service not running",
"linkLanMode": "Looking for devices on this network",
@@ -160,6 +161,7 @@
"filterText": "Text",
"filterImage": "Images",
"filterFile": "Files",
+ "filterLink": "Links",
"historyClearTooltip": "Clear history",
"historyEmptyTitle": "Nothing here yet",
"historyEmptyFilteredTitle": "Nothing of this kind",
@@ -223,6 +225,175 @@
}
},
"searchEmptyBody": "Search looks through copied text and the names of copied files.",
+ "favoriteAction": "Add to favorites",
+ "unfavoriteAction": "Remove from favorites",
+ "favoritedToast": "Added to Favorites",
+ "unfavoritedToast": "Moved back to History",
+ "undo": "Undo",
+ "favoriteSaving": "Saving…",
+ "favoritedAt": "Saved {date}",
+ "@favoritedAt": {
+ "placeholders": {
+ "date": {
+ "type": "String"
+ }
+ }
+ },
+ "favoritesSubtitle": "{count, plural, =1{1 item} other{{count} items}} · never cleaned up · up to {size}",
+ "@favoritesSubtitle": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ },
+ "size": {
+ "type": "String"
+ }
+ }
+ },
+ "favoritesEmptyTitle": "No favorites yet",
+ "favoritesEmptyBody": "Star an item in History to keep a copy here. Favorites are never cleaned up automatically.",
+ "favoritesSearchHint": "Search favorites",
+ "favoriteLargeTitle": "Save a copy of {size}?",
+ "@favoriteLargeTitle": {
+ "placeholders": {
+ "size": {
+ "type": "String"
+ }
+ }
+ },
+ "favoriteLargeBody": "A favorite keeps its own copy, so changing or deleting the original files won't affect it. This uses {size} on {device}.",
+ "@favoriteLargeBody": {
+ "placeholders": {
+ "size": {
+ "type": "String"
+ },
+ "device": {
+ "type": "String"
+ }
+ }
+ },
+ "saveCopy": "Save copy",
+ "clearKeepsFavorites": "{count, plural, =1{Your 1 favorite stays.} other{Your {count} favorites stay.}}",
+ "@clearKeepsFavorites": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "favoritesUsage": "Favorites",
+ "favoritesUsageDesc": "Favorites are never cleaned up, whatever the settings above",
+ "upToSize": "Up to {size}",
+ "@upToSize": {
+ "placeholders": {
+ "size": {
+ "type": "String"
+ }
+ }
+ },
+ "detailChars": "{count, plural, =1{1 character} other{{count} characters}}",
+ "@detailChars": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "detailTruncated": "… {count} characters in total",
+ "@detailTruncated": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "detailMoreFiles": "{count, plural, =1{1 more} other{{count} more}}",
+ "@detailMoreFiles": {
+ "placeholders": {
+ "count": {
+ "type": "int"
+ }
+ }
+ },
+ "detailReceiveFirst": "Pick it to download it first",
+ "detailTotalSize": "{size} in total",
+ "@detailTotalSize": {
+ "placeholders": {
+ "size": {
+ "type": "String"
+ }
+ }
+ },
+ "quickPaste": "Quick paste",
+ "quickPasteWindow": "Quick paste window",
+ "quickPasteWindowDesc": "Press the shortcut in any app to bring up your history; pick an item and it's pasted",
+ "quickPasteShortcut": "Shortcut",
+ "quickPasteRecord": "Click to change",
+ "quickPasteRecording": "Press the new shortcut…",
+ "quickPasteUseDefault": "Use default",
+ "quickPasteNeedsModifier": "Include ⌃, ⌥, ⇧ or ⌘, or use a function key",
+ "quickPasteNeedsModifierPc": "Include Ctrl, Alt, Shift or the Windows key, or use a function key",
+ "quickPasteAfterPick": "After you pick an item",
+ "quickPastePasteIt": "Paste it",
+ "quickPasteCopyIt": "Just copy it",
+ "quickPasteAccessibility": "Accessibility",
+ "quickPasteAccessibilityDesc": "Needed to paste for you. Without it, items are copied and you press ⌘V.",
+ "quickPasteAllowed": "Allowed",
+ "quickPasteAllow": "Allow…",
+ "quickPasteNotRunning": "The quick paste window isn't running",
+ "quickPasteInUse": "{key} is used by another app. Pick another shortcut.",
+ "@quickPasteInUse": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ }
+ }
+ },
+ "quickPasteHotkeyFailed": "Couldn't set {key}: {detail}",
+ "@quickPasteHotkeyFailed": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ },
+ "detail": {
+ "type": "String"
+ }
+ }
+ },
+ "quickPastePortalKey": "Set in the system shortcut settings",
+ "quickPasteWaylandDesc": "On Wayland, add the shortcut in your desktop's keyboard settings. Picked items are copied; press Ctrl+V to paste.",
+ "quickPasteAddShortcut": "Add system shortcut",
+ "quickPasteShortcutAdded": "Added. Press {key} to try it.",
+ "@quickPasteShortcutAdded": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ }
+ }
+ },
+ "quickPasteShortcutManual": "Add a custom shortcut in your desktop's keyboard settings that runs: {command}",
+ "@quickPasteShortcutManual": {
+ "placeholders": {
+ "command": {
+ "type": "String"
+ }
+ }
+ },
+ "pickerSearch": "Search",
+ "pickerPaste": "Paste",
+ "pickerPlainText": "Plain text",
+ "pickerCopyOnly": "Copy only",
+ "pickerUnfavoriteHint": "Remove (back to History)",
+ "pickerPasteManually": "Picked items are copied — press {key} to paste",
+ "@pickerPasteManually": {
+ "placeholders": {
+ "key": {
+ "type": "String"
+ }
+ }
+ },
+ "pickerGrantHint": "Allow Accessibility to paste directly",
+ "pickerDownloading": "Downloading — pastes when done",
"imagePreviewTitle": "Image preview",
"closePreview": "Close preview",
"previousImage": "Previous image",
diff --git a/ui/lib/l10n/app_ja.arb b/ui/lib/l10n/app_ja.arb
index 3d8f9ae..e64d77d 100644
--- a/ui/lib/l10n/app_ja.arb
+++ b/ui/lib/l10n/app_ja.arb
@@ -4,6 +4,7 @@
"navHistory": "履歴",
"navDevices": "デバイス",
"navSettings": "設定",
+ "navFavorites": "お気に入り",
"linkConnecting": "接続中…",
"linkServiceNotRunning": "サービス停止中",
"linkLanMode": "このネットワークでデバイスを探しています",
@@ -49,6 +50,7 @@
"filterText": "テキスト",
"filterImage": "画像",
"filterFile": "ファイル",
+ "filterLink": "リンク",
"historyClearTooltip": "履歴を消去",
"historyEmptyTitle": "まだ履歴がありません",
"historyEmptyFilteredTitle": "この種類の履歴はありません",
@@ -78,6 +80,61 @@
"searchResultCount": "{count} 件見つかりました",
"searchEmptyTitle": "「{query}」は見つかりません",
"searchEmptyBody": "コピーしたテキストとファイル名から検索します。",
+ "favoriteAction": "お気に入りに追加",
+ "unfavoriteAction": "お気に入りから外す",
+ "favoritedToast": "お気に入りに追加しました",
+ "unfavoritedToast": "履歴に戻しました",
+ "undo": "元に戻す",
+ "favoriteSaving": "保存中…",
+ "favoritedAt": "{date} に保存",
+ "favoritesSubtitle": "{count} 件・自動では削除されません・最大 {size}",
+ "favoritesEmptyTitle": "お気に入りはまだありません",
+ "favoritesEmptyBody": "履歴で星をクリックすると、ここにコピーが保存されます。お気に入りは自動では削除されません。",
+ "favoritesSearchHint": "お気に入りを検索",
+ "favoriteLargeTitle": "{size} のコピーを保存しますか?",
+ "favoriteLargeBody": "お気に入りは独自のコピーを保存するため、元のファイルを変更・削除しても影響を受けません。{device}の {size} を使用します。",
+ "saveCopy": "保存",
+ "clearKeepsFavorites": "お気に入りの {count} 件は残ります。",
+ "favoritesUsage": "お気に入りの使用量",
+ "favoritesUsageDesc": "お気に入りは上の設定にかかわらず自動では削除されません",
+ "upToSize": "最大 {size}",
+ "detailChars": "{count} 文字",
+ "detailTruncated": "…(全 {count} 文字)",
+ "detailMoreFiles": "ほか {count} 件",
+ "detailReceiveFirst": "選ぶと先にダウンロードします",
+ "detailTotalSize": "合計 {size}",
+ "quickPaste": "クイックペースト",
+ "quickPasteWindow": "クイックペーストウィンドウ",
+ "quickPasteWindowDesc": "どのアプリでもショートカットで履歴を表示し、選ぶとペーストします",
+ "quickPasteShortcut": "ショートカット",
+ "quickPasteRecord": "クリックして変更",
+ "quickPasteRecording": "新しいショートカットを押してください…",
+ "quickPasteUseDefault": "デフォルトに戻す",
+ "quickPasteNeedsModifier": "⌃、⌥、⇧、⌘ のいずれかを含めるか、ファンクションキーを使ってください",
+ "quickPasteNeedsModifierPc": "Ctrl、Alt、Shift、Windows キーのいずれかを含めるか、ファンクションキーを使ってください",
+ "quickPasteAfterPick": "選んだ後",
+ "quickPastePasteIt": "ペーストする",
+ "quickPasteCopyIt": "コピーのみ",
+ "quickPasteAccessibility": "アクセシビリティ",
+ "quickPasteAccessibilityDesc": "ペーストするのに必要です。許可しない場合はコピーだけされ、⌘V で貼り付けます。",
+ "quickPasteAllowed": "許可済み",
+ "quickPasteAllow": "許可する…",
+ "quickPasteNotRunning": "クイックペーストウィンドウが起動していません",
+ "quickPasteInUse": "{key} は別のアプリが使用しています。別のショートカットを選んでください。",
+ "quickPasteHotkeyFailed": "{key} を設定できませんでした:{detail}",
+ "quickPastePortalKey": "システムのショートカット設定で変更します",
+ "quickPasteWaylandDesc": "Wayland ではデスクトップのキーボード設定でショートカットを追加します。選ぶとコピーされるので、Ctrl+V で貼り付けてください。",
+ "quickPasteAddShortcut": "システムのショートカットを追加",
+ "quickPasteShortcutAdded": "追加しました。{key} を押して試してください。",
+ "quickPasteShortcutManual": "デスクトップのキーボード設定で、次のコマンドを実行するカスタムショートカットを追加してください:{command}",
+ "pickerSearch": "検索",
+ "pickerPaste": "ペースト",
+ "pickerPlainText": "プレーンテキスト",
+ "pickerCopyOnly": "コピーのみ",
+ "pickerUnfavoriteHint": "お気に入りから外す(履歴に戻す)",
+ "pickerPasteManually": "選ぶとコピーされます。{key} で貼り付けてください",
+ "pickerGrantHint": "アクセシビリティを許可すると直接ペーストできます",
+ "pickerDownloading": "ダウンロード中。完了するとペーストします",
"imagePreviewTitle": "画像プレビュー",
"closePreview": "プレビューを閉じる",
"previousImage": "前の画像",
diff --git a/ui/lib/l10n/app_localizations.dart b/ui/lib/l10n/app_localizations.dart
index 5574e43..83505f1 100644
--- a/ui/lib/l10n/app_localizations.dart
+++ b/ui/lib/l10n/app_localizations.dart
@@ -134,6 +134,12 @@ abstract class AppLocalizations {
/// **'Settings'**
String get navSettings;
+ /// No description provided for @navFavorites.
+ ///
+ /// In en, this message translates to:
+ /// **'Favorites'**
+ String get navFavorites;
+
/// No description provided for @linkConnecting.
///
/// In en, this message translates to:
@@ -404,6 +410,12 @@ abstract class AppLocalizations {
/// **'Files'**
String get filterFile;
+ /// No description provided for @filterLink.
+ ///
+ /// In en, this message translates to:
+ /// **'Links'**
+ String get filterLink;
+
/// No description provided for @historyClearTooltip.
///
/// In en, this message translates to:
@@ -578,6 +590,336 @@ abstract class AppLocalizations {
/// **'Search looks through copied text and the names of copied files.'**
String get searchEmptyBody;
+ /// No description provided for @favoriteAction.
+ ///
+ /// In en, this message translates to:
+ /// **'Add to favorites'**
+ String get favoriteAction;
+
+ /// No description provided for @unfavoriteAction.
+ ///
+ /// In en, this message translates to:
+ /// **'Remove from favorites'**
+ String get unfavoriteAction;
+
+ /// No description provided for @favoritedToast.
+ ///
+ /// In en, this message translates to:
+ /// **'Added to Favorites'**
+ String get favoritedToast;
+
+ /// No description provided for @unfavoritedToast.
+ ///
+ /// In en, this message translates to:
+ /// **'Moved back to History'**
+ String get unfavoritedToast;
+
+ /// No description provided for @undo.
+ ///
+ /// In en, this message translates to:
+ /// **'Undo'**
+ String get undo;
+
+ /// No description provided for @favoriteSaving.
+ ///
+ /// In en, this message translates to:
+ /// **'Saving…'**
+ String get favoriteSaving;
+
+ /// No description provided for @favoritedAt.
+ ///
+ /// In en, this message translates to:
+ /// **'Saved {date}'**
+ String favoritedAt(String date);
+
+ /// No description provided for @favoritesSubtitle.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{1 item} other{{count} items}} · never cleaned up · up to {size}'**
+ String favoritesSubtitle(int count, String size);
+
+ /// No description provided for @favoritesEmptyTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'No favorites yet'**
+ String get favoritesEmptyTitle;
+
+ /// No description provided for @favoritesEmptyBody.
+ ///
+ /// In en, this message translates to:
+ /// **'Star an item in History to keep a copy here. Favorites are never cleaned up automatically.'**
+ String get favoritesEmptyBody;
+
+ /// No description provided for @favoritesSearchHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Search favorites'**
+ String get favoritesSearchHint;
+
+ /// No description provided for @favoriteLargeTitle.
+ ///
+ /// In en, this message translates to:
+ /// **'Save a copy of {size}?'**
+ String favoriteLargeTitle(String size);
+
+ /// No description provided for @favoriteLargeBody.
+ ///
+ /// In en, this message translates to:
+ /// **'A favorite keeps its own copy, so changing or deleting the original files won\'t affect it. This uses {size} on {device}.'**
+ String favoriteLargeBody(String size, String device);
+
+ /// No description provided for @saveCopy.
+ ///
+ /// In en, this message translates to:
+ /// **'Save copy'**
+ String get saveCopy;
+
+ /// No description provided for @clearKeepsFavorites.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{Your 1 favorite stays.} other{Your {count} favorites stay.}}'**
+ String clearKeepsFavorites(int count);
+
+ /// No description provided for @favoritesUsage.
+ ///
+ /// In en, this message translates to:
+ /// **'Favorites'**
+ String get favoritesUsage;
+
+ /// No description provided for @favoritesUsageDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Favorites are never cleaned up, whatever the settings above'**
+ String get favoritesUsageDesc;
+
+ /// No description provided for @upToSize.
+ ///
+ /// In en, this message translates to:
+ /// **'Up to {size}'**
+ String upToSize(String size);
+
+ /// No description provided for @detailChars.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{1 character} other{{count} characters}}'**
+ String detailChars(int count);
+
+ /// No description provided for @detailTruncated.
+ ///
+ /// In en, this message translates to:
+ /// **'… {count} characters in total'**
+ String detailTruncated(int count);
+
+ /// No description provided for @detailMoreFiles.
+ ///
+ /// In en, this message translates to:
+ /// **'{count, plural, =1{1 more} other{{count} more}}'**
+ String detailMoreFiles(int count);
+
+ /// No description provided for @detailReceiveFirst.
+ ///
+ /// In en, this message translates to:
+ /// **'Pick it to download it first'**
+ String get detailReceiveFirst;
+
+ /// No description provided for @detailTotalSize.
+ ///
+ /// In en, this message translates to:
+ /// **'{size} in total'**
+ String detailTotalSize(String size);
+
+ /// No description provided for @quickPaste.
+ ///
+ /// In en, this message translates to:
+ /// **'Quick paste'**
+ String get quickPaste;
+
+ /// No description provided for @quickPasteWindow.
+ ///
+ /// In en, this message translates to:
+ /// **'Quick paste window'**
+ String get quickPasteWindow;
+
+ /// No description provided for @quickPasteWindowDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Press the shortcut in any app to bring up your history; pick an item and it\'s pasted'**
+ String get quickPasteWindowDesc;
+
+ /// No description provided for @quickPasteShortcut.
+ ///
+ /// In en, this message translates to:
+ /// **'Shortcut'**
+ String get quickPasteShortcut;
+
+ /// No description provided for @quickPasteRecord.
+ ///
+ /// In en, this message translates to:
+ /// **'Click to change'**
+ String get quickPasteRecord;
+
+ /// No description provided for @quickPasteRecording.
+ ///
+ /// In en, this message translates to:
+ /// **'Press the new shortcut…'**
+ String get quickPasteRecording;
+
+ /// No description provided for @quickPasteUseDefault.
+ ///
+ /// In en, this message translates to:
+ /// **'Use default'**
+ String get quickPasteUseDefault;
+
+ /// No description provided for @quickPasteNeedsModifier.
+ ///
+ /// In en, this message translates to:
+ /// **'Include ⌃, ⌥, ⇧ or ⌘, or use a function key'**
+ String get quickPasteNeedsModifier;
+
+ /// No description provided for @quickPasteNeedsModifierPc.
+ ///
+ /// In en, this message translates to:
+ /// **'Include Ctrl, Alt, Shift or the Windows key, or use a function key'**
+ String get quickPasteNeedsModifierPc;
+
+ /// No description provided for @quickPasteAfterPick.
+ ///
+ /// In en, this message translates to:
+ /// **'After you pick an item'**
+ String get quickPasteAfterPick;
+
+ /// No description provided for @quickPastePasteIt.
+ ///
+ /// In en, this message translates to:
+ /// **'Paste it'**
+ String get quickPastePasteIt;
+
+ /// No description provided for @quickPasteCopyIt.
+ ///
+ /// In en, this message translates to:
+ /// **'Just copy it'**
+ String get quickPasteCopyIt;
+
+ /// No description provided for @quickPasteAccessibility.
+ ///
+ /// In en, this message translates to:
+ /// **'Accessibility'**
+ String get quickPasteAccessibility;
+
+ /// No description provided for @quickPasteAccessibilityDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'Needed to paste for you. Without it, items are copied and you press ⌘V.'**
+ String get quickPasteAccessibilityDesc;
+
+ /// No description provided for @quickPasteAllowed.
+ ///
+ /// In en, this message translates to:
+ /// **'Allowed'**
+ String get quickPasteAllowed;
+
+ /// No description provided for @quickPasteAllow.
+ ///
+ /// In en, this message translates to:
+ /// **'Allow…'**
+ String get quickPasteAllow;
+
+ /// No description provided for @quickPasteNotRunning.
+ ///
+ /// In en, this message translates to:
+ /// **'The quick paste window isn\'t running'**
+ String get quickPasteNotRunning;
+
+ /// No description provided for @quickPasteInUse.
+ ///
+ /// In en, this message translates to:
+ /// **'{key} is used by another app. Pick another shortcut.'**
+ String quickPasteInUse(String key);
+
+ /// No description provided for @quickPasteHotkeyFailed.
+ ///
+ /// In en, this message translates to:
+ /// **'Couldn\'t set {key}: {detail}'**
+ String quickPasteHotkeyFailed(String key, String detail);
+
+ /// No description provided for @quickPastePortalKey.
+ ///
+ /// In en, this message translates to:
+ /// **'Set in the system shortcut settings'**
+ String get quickPastePortalKey;
+
+ /// No description provided for @quickPasteWaylandDesc.
+ ///
+ /// In en, this message translates to:
+ /// **'On Wayland, add the shortcut in your desktop\'s keyboard settings. Picked items are copied; press Ctrl+V to paste.'**
+ String get quickPasteWaylandDesc;
+
+ /// No description provided for @quickPasteAddShortcut.
+ ///
+ /// In en, this message translates to:
+ /// **'Add system shortcut'**
+ String get quickPasteAddShortcut;
+
+ /// No description provided for @quickPasteShortcutAdded.
+ ///
+ /// In en, this message translates to:
+ /// **'Added. Press {key} to try it.'**
+ String quickPasteShortcutAdded(String key);
+
+ /// No description provided for @quickPasteShortcutManual.
+ ///
+ /// In en, this message translates to:
+ /// **'Add a custom shortcut in your desktop\'s keyboard settings that runs: {command}'**
+ String quickPasteShortcutManual(String command);
+
+ /// No description provided for @pickerSearch.
+ ///
+ /// In en, this message translates to:
+ /// **'Search'**
+ String get pickerSearch;
+
+ /// No description provided for @pickerPaste.
+ ///
+ /// In en, this message translates to:
+ /// **'Paste'**
+ String get pickerPaste;
+
+ /// No description provided for @pickerPlainText.
+ ///
+ /// In en, this message translates to:
+ /// **'Plain text'**
+ String get pickerPlainText;
+
+ /// No description provided for @pickerCopyOnly.
+ ///
+ /// In en, this message translates to:
+ /// **'Copy only'**
+ String get pickerCopyOnly;
+
+ /// No description provided for @pickerUnfavoriteHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Remove (back to History)'**
+ String get pickerUnfavoriteHint;
+
+ /// No description provided for @pickerPasteManually.
+ ///
+ /// In en, this message translates to:
+ /// **'Picked items are copied — press {key} to paste'**
+ String pickerPasteManually(String key);
+
+ /// No description provided for @pickerGrantHint.
+ ///
+ /// In en, this message translates to:
+ /// **'Allow Accessibility to paste directly'**
+ String get pickerGrantHint;
+
+ /// No description provided for @pickerDownloading.
+ ///
+ /// In en, this message translates to:
+ /// **'Downloading — pastes when done'**
+ String get pickerDownloading;
+
/// No description provided for @imagePreviewTitle.
///
/// In en, this message translates to:
diff --git a/ui/lib/l10n/app_localizations_en.dart b/ui/lib/l10n/app_localizations_en.dart
index eddb0b3..f7fa14e 100644
--- a/ui/lib/l10n/app_localizations_en.dart
+++ b/ui/lib/l10n/app_localizations_en.dart
@@ -20,6 +20,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get navSettings => 'Settings';
+ @override
+ String get navFavorites => 'Favorites';
+
@override
String get linkConnecting => 'Connecting…';
@@ -237,6 +240,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get filterFile => 'Files';
+ @override
+ String get filterLink => 'Links';
+
@override
String get historyClearTooltip => 'Clear history';
@@ -348,6 +354,232 @@ class AppLocalizationsEn extends AppLocalizations {
String get searchEmptyBody =>
'Search looks through copied text and the names of copied files.';
+ @override
+ String get favoriteAction => 'Add to favorites';
+
+ @override
+ String get unfavoriteAction => 'Remove from favorites';
+
+ @override
+ String get favoritedToast => 'Added to Favorites';
+
+ @override
+ String get unfavoritedToast => 'Moved back to History';
+
+ @override
+ String get undo => 'Undo';
+
+ @override
+ String get favoriteSaving => 'Saving…';
+
+ @override
+ String favoritedAt(String date) {
+ return 'Saved $date';
+ }
+
+ @override
+ String favoritesSubtitle(int count, String size) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count items',
+ one: '1 item',
+ );
+ return '$_temp0 · never cleaned up · up to $size';
+ }
+
+ @override
+ String get favoritesEmptyTitle => 'No favorites yet';
+
+ @override
+ String get favoritesEmptyBody =>
+ 'Star an item in History to keep a copy here. Favorites are never cleaned up automatically.';
+
+ @override
+ String get favoritesSearchHint => 'Search favorites';
+
+ @override
+ String favoriteLargeTitle(String size) {
+ return 'Save a copy of $size?';
+ }
+
+ @override
+ String favoriteLargeBody(String size, String device) {
+ return 'A favorite keeps its own copy, so changing or deleting the original files won\'t affect it. This uses $size on $device.';
+ }
+
+ @override
+ String get saveCopy => 'Save copy';
+
+ @override
+ String clearKeepsFavorites(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: 'Your $count favorites stay.',
+ one: 'Your 1 favorite stays.',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get favoritesUsage => 'Favorites';
+
+ @override
+ String get favoritesUsageDesc =>
+ 'Favorites are never cleaned up, whatever the settings above';
+
+ @override
+ String upToSize(String size) {
+ return 'Up to $size';
+ }
+
+ @override
+ String detailChars(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count characters',
+ one: '1 character',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String detailTruncated(int count) {
+ return '… $count characters in total';
+ }
+
+ @override
+ String detailMoreFiles(int count) {
+ String _temp0 = intl.Intl.pluralLogic(
+ count,
+ locale: localeName,
+ other: '$count more',
+ one: '1 more',
+ );
+ return '$_temp0';
+ }
+
+ @override
+ String get detailReceiveFirst => 'Pick it to download it first';
+
+ @override
+ String detailTotalSize(String size) {
+ return '$size in total';
+ }
+
+ @override
+ String get quickPaste => 'Quick paste';
+
+ @override
+ String get quickPasteWindow => 'Quick paste window';
+
+ @override
+ String get quickPasteWindowDesc =>
+ 'Press the shortcut in any app to bring up your history; pick an item and it\'s pasted';
+
+ @override
+ String get quickPasteShortcut => 'Shortcut';
+
+ @override
+ String get quickPasteRecord => 'Click to change';
+
+ @override
+ String get quickPasteRecording => 'Press the new shortcut…';
+
+ @override
+ String get quickPasteUseDefault => 'Use default';
+
+ @override
+ String get quickPasteNeedsModifier =>
+ 'Include ⌃, ⌥, ⇧ or ⌘, or use a function key';
+
+ @override
+ String get quickPasteNeedsModifierPc =>
+ 'Include Ctrl, Alt, Shift or the Windows key, or use a function key';
+
+ @override
+ String get quickPasteAfterPick => 'After you pick an item';
+
+ @override
+ String get quickPastePasteIt => 'Paste it';
+
+ @override
+ String get quickPasteCopyIt => 'Just copy it';
+
+ @override
+ String get quickPasteAccessibility => 'Accessibility';
+
+ @override
+ String get quickPasteAccessibilityDesc =>
+ 'Needed to paste for you. Without it, items are copied and you press ⌘V.';
+
+ @override
+ String get quickPasteAllowed => 'Allowed';
+
+ @override
+ String get quickPasteAllow => 'Allow…';
+
+ @override
+ String get quickPasteNotRunning => 'The quick paste window isn\'t running';
+
+ @override
+ String quickPasteInUse(String key) {
+ return '$key is used by another app. Pick another shortcut.';
+ }
+
+ @override
+ String quickPasteHotkeyFailed(String key, String detail) {
+ return 'Couldn\'t set $key: $detail';
+ }
+
+ @override
+ String get quickPastePortalKey => 'Set in the system shortcut settings';
+
+ @override
+ String get quickPasteWaylandDesc =>
+ 'On Wayland, add the shortcut in your desktop\'s keyboard settings. Picked items are copied; press Ctrl+V to paste.';
+
+ @override
+ String get quickPasteAddShortcut => 'Add system shortcut';
+
+ @override
+ String quickPasteShortcutAdded(String key) {
+ return 'Added. Press $key to try it.';
+ }
+
+ @override
+ String quickPasteShortcutManual(String command) {
+ return 'Add a custom shortcut in your desktop\'s keyboard settings that runs: $command';
+ }
+
+ @override
+ String get pickerSearch => 'Search';
+
+ @override
+ String get pickerPaste => 'Paste';
+
+ @override
+ String get pickerPlainText => 'Plain text';
+
+ @override
+ String get pickerCopyOnly => 'Copy only';
+
+ @override
+ String get pickerUnfavoriteHint => 'Remove (back to History)';
+
+ @override
+ String pickerPasteManually(String key) {
+ return 'Picked items are copied — press $key to paste';
+ }
+
+ @override
+ String get pickerGrantHint => 'Allow Accessibility to paste directly';
+
+ @override
+ String get pickerDownloading => 'Downloading — pastes when done';
+
@override
String get imagePreviewTitle => 'Image preview';
diff --git a/ui/lib/l10n/app_localizations_ja.dart b/ui/lib/l10n/app_localizations_ja.dart
index 119ff38..564037b 100644
--- a/ui/lib/l10n/app_localizations_ja.dart
+++ b/ui/lib/l10n/app_localizations_ja.dart
@@ -20,6 +20,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get navSettings => '設定';
+ @override
+ String get navFavorites => 'お気に入り';
+
@override
String get linkConnecting => '接続中…';
@@ -185,6 +188,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get filterFile => 'ファイル';
+ @override
+ String get filterLink => 'リンク';
+
@override
String get historyClearTooltip => '履歴を消去';
@@ -282,6 +288,205 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get searchEmptyBody => 'コピーしたテキストとファイル名から検索します。';
+ @override
+ String get favoriteAction => 'お気に入りに追加';
+
+ @override
+ String get unfavoriteAction => 'お気に入りから外す';
+
+ @override
+ String get favoritedToast => 'お気に入りに追加しました';
+
+ @override
+ String get unfavoritedToast => '履歴に戻しました';
+
+ @override
+ String get undo => '元に戻す';
+
+ @override
+ String get favoriteSaving => '保存中…';
+
+ @override
+ String favoritedAt(String date) {
+ return '$date に保存';
+ }
+
+ @override
+ String favoritesSubtitle(int count, String size) {
+ return '$count 件・自動では削除されません・最大 $size';
+ }
+
+ @override
+ String get favoritesEmptyTitle => 'お気に入りはまだありません';
+
+ @override
+ String get favoritesEmptyBody =>
+ '履歴で星をクリックすると、ここにコピーが保存されます。お気に入りは自動では削除されません。';
+
+ @override
+ String get favoritesSearchHint => 'お気に入りを検索';
+
+ @override
+ String favoriteLargeTitle(String size) {
+ return '$size のコピーを保存しますか?';
+ }
+
+ @override
+ String favoriteLargeBody(String size, String device) {
+ return 'お気に入りは独自のコピーを保存するため、元のファイルを変更・削除しても影響を受けません。$deviceの $size を使用します。';
+ }
+
+ @override
+ String get saveCopy => '保存';
+
+ @override
+ String clearKeepsFavorites(int count) {
+ return 'お気に入りの $count 件は残ります。';
+ }
+
+ @override
+ String get favoritesUsage => 'お気に入りの使用量';
+
+ @override
+ String get favoritesUsageDesc => 'お気に入りは上の設定にかかわらず自動では削除されません';
+
+ @override
+ String upToSize(String size) {
+ return '最大 $size';
+ }
+
+ @override
+ String detailChars(int count) {
+ return '$count 文字';
+ }
+
+ @override
+ String detailTruncated(int count) {
+ return '…(全 $count 文字)';
+ }
+
+ @override
+ String detailMoreFiles(int count) {
+ return 'ほか $count 件';
+ }
+
+ @override
+ String get detailReceiveFirst => '選ぶと先にダウンロードします';
+
+ @override
+ String detailTotalSize(String size) {
+ return '合計 $size';
+ }
+
+ @override
+ String get quickPaste => 'クイックペースト';
+
+ @override
+ String get quickPasteWindow => 'クイックペーストウィンドウ';
+
+ @override
+ String get quickPasteWindowDesc => 'どのアプリでもショートカットで履歴を表示し、選ぶとペーストします';
+
+ @override
+ String get quickPasteShortcut => 'ショートカット';
+
+ @override
+ String get quickPasteRecord => 'クリックして変更';
+
+ @override
+ String get quickPasteRecording => '新しいショートカットを押してください…';
+
+ @override
+ String get quickPasteUseDefault => 'デフォルトに戻す';
+
+ @override
+ String get quickPasteNeedsModifier => '⌃、⌥、⇧、⌘ のいずれかを含めるか、ファンクションキーを使ってください';
+
+ @override
+ String get quickPasteNeedsModifierPc =>
+ 'Ctrl、Alt、Shift、Windows キーのいずれかを含めるか、ファンクションキーを使ってください';
+
+ @override
+ String get quickPasteAfterPick => '選んだ後';
+
+ @override
+ String get quickPastePasteIt => 'ペーストする';
+
+ @override
+ String get quickPasteCopyIt => 'コピーのみ';
+
+ @override
+ String get quickPasteAccessibility => 'アクセシビリティ';
+
+ @override
+ String get quickPasteAccessibilityDesc =>
+ 'ペーストするのに必要です。許可しない場合はコピーだけされ、⌘V で貼り付けます。';
+
+ @override
+ String get quickPasteAllowed => '許可済み';
+
+ @override
+ String get quickPasteAllow => '許可する…';
+
+ @override
+ String get quickPasteNotRunning => 'クイックペーストウィンドウが起動していません';
+
+ @override
+ String quickPasteInUse(String key) {
+ return '$key は別のアプリが使用しています。別のショートカットを選んでください。';
+ }
+
+ @override
+ String quickPasteHotkeyFailed(String key, String detail) {
+ return '$key を設定できませんでした:$detail';
+ }
+
+ @override
+ String get quickPastePortalKey => 'システムのショートカット設定で変更します';
+
+ @override
+ String get quickPasteWaylandDesc =>
+ 'Wayland ではデスクトップのキーボード設定でショートカットを追加します。選ぶとコピーされるので、Ctrl+V で貼り付けてください。';
+
+ @override
+ String get quickPasteAddShortcut => 'システムのショートカットを追加';
+
+ @override
+ String quickPasteShortcutAdded(String key) {
+ return '追加しました。$key を押して試してください。';
+ }
+
+ @override
+ String quickPasteShortcutManual(String command) {
+ return 'デスクトップのキーボード設定で、次のコマンドを実行するカスタムショートカットを追加してください:$command';
+ }
+
+ @override
+ String get pickerSearch => '検索';
+
+ @override
+ String get pickerPaste => 'ペースト';
+
+ @override
+ String get pickerPlainText => 'プレーンテキスト';
+
+ @override
+ String get pickerCopyOnly => 'コピーのみ';
+
+ @override
+ String get pickerUnfavoriteHint => 'お気に入りから外す(履歴に戻す)';
+
+ @override
+ String pickerPasteManually(String key) {
+ return '選ぶとコピーされます。$key で貼り付けてください';
+ }
+
+ @override
+ String get pickerGrantHint => 'アクセシビリティを許可すると直接ペーストできます';
+
+ @override
+ String get pickerDownloading => 'ダウンロード中。完了するとペーストします';
+
@override
String get imagePreviewTitle => '画像プレビュー';
diff --git a/ui/lib/l10n/app_localizations_zh.dart b/ui/lib/l10n/app_localizations_zh.dart
index 0ae1e9a..5fa8d0b 100644
--- a/ui/lib/l10n/app_localizations_zh.dart
+++ b/ui/lib/l10n/app_localizations_zh.dart
@@ -20,6 +20,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get navSettings => '设置';
+ @override
+ String get navFavorites => '收藏';
+
@override
String get linkConnecting => '正在连接…';
@@ -185,6 +188,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get filterFile => '文件';
+ @override
+ String get filterLink => '链接';
+
@override
String get historyClearTooltip => '清空记录';
@@ -282,6 +288,202 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get searchEmptyBody => '搜索的是复制过的文字和文件名。';
+ @override
+ String get favoriteAction => '收藏';
+
+ @override
+ String get unfavoriteAction => '取消收藏';
+
+ @override
+ String get favoritedToast => '已收藏';
+
+ @override
+ String get unfavoritedToast => '已放回复制记录';
+
+ @override
+ String get undo => '撤销';
+
+ @override
+ String get favoriteSaving => '正在保存…';
+
+ @override
+ String favoritedAt(String date) {
+ return '收藏于 $date';
+ }
+
+ @override
+ String favoritesSubtitle(int count, String size) {
+ return '$count 条 · 不会被自动清理 · 最多占用 $size';
+ }
+
+ @override
+ String get favoritesEmptyTitle => '还没有收藏';
+
+ @override
+ String get favoritesEmptyBody => '在复制记录里点星标,就会在这里另存一份。收藏不会被自动清理。';
+
+ @override
+ String get favoritesSearchHint => '搜索收藏';
+
+ @override
+ String favoriteLargeTitle(String size) {
+ return '另存一份 $size 的内容?';
+ }
+
+ @override
+ String favoriteLargeBody(String size, String device) {
+ return '收藏会另存一份,原文件之后改动或删除都不影响收藏。这会占用$device上 $size 的空间。';
+ }
+
+ @override
+ String get saveCopy => '另存';
+
+ @override
+ String clearKeepsFavorites(int count) {
+ return '已收藏的 $count 条会保留。';
+ }
+
+ @override
+ String get favoritesUsage => '收藏占用';
+
+ @override
+ String get favoritesUsageDesc => '收藏不受上面两项的限制,不会被自动清理';
+
+ @override
+ String upToSize(String size) {
+ return '最多 $size';
+ }
+
+ @override
+ String detailChars(int count) {
+ return '$count 字';
+ }
+
+ @override
+ String detailTruncated(int count) {
+ return '…… 共 $count 字';
+ }
+
+ @override
+ String detailMoreFiles(int count) {
+ return '还有 $count 个';
+ }
+
+ @override
+ String get detailReceiveFirst => '选中后先下载';
+
+ @override
+ String detailTotalSize(String size) {
+ return '共 $size';
+ }
+
+ @override
+ String get quickPaste => '快捷粘贴';
+
+ @override
+ String get quickPasteWindow => '快捷粘贴窗口';
+
+ @override
+ String get quickPasteWindowDesc => '在任何程序里按快捷键呼出复制记录,选中即粘贴';
+
+ @override
+ String get quickPasteShortcut => '快捷键';
+
+ @override
+ String get quickPasteRecord => '点击录制';
+
+ @override
+ String get quickPasteRecording => '请按下新的快捷键…';
+
+ @override
+ String get quickPasteUseDefault => '恢复默认';
+
+ @override
+ String get quickPasteNeedsModifier => '要带上 ⌃、⌥、⇧ 或 ⌘,或者用功能键';
+
+ @override
+ String get quickPasteNeedsModifierPc => '要带上 Ctrl、Alt、Shift 或 Win 键,或者用功能键';
+
+ @override
+ String get quickPasteAfterPick => '选中后';
+
+ @override
+ String get quickPastePasteIt => '直接粘贴';
+
+ @override
+ String get quickPasteCopyIt => '只放进剪贴板';
+
+ @override
+ String get quickPasteAccessibility => '辅助功能权限';
+
+ @override
+ String get quickPasteAccessibilityDesc => '直接粘贴需要它;没有授权时只放进剪贴板,再由你按 ⌘V';
+
+ @override
+ String get quickPasteAllowed => '已授权';
+
+ @override
+ String get quickPasteAllow => '去授权';
+
+ @override
+ String get quickPasteNotRunning => '快捷粘贴窗口没有运行';
+
+ @override
+ String quickPasteInUse(String key) {
+ return '$key 已被其他程序占用,换一个组合';
+ }
+
+ @override
+ String quickPasteHotkeyFailed(String key, String detail) {
+ return '设置 $key 失败:$detail';
+ }
+
+ @override
+ String get quickPastePortalKey => '在系统的快捷键设置里修改';
+
+ @override
+ String get quickPasteWaylandDesc =>
+ 'Wayland 下快捷键要加在桌面的键盘设置里;选中后放进剪贴板,再按 Ctrl+V 粘贴';
+
+ @override
+ String get quickPasteAddShortcut => '添加系统快捷键';
+
+ @override
+ String quickPasteShortcutAdded(String key) {
+ return '已添加,按 $key 试试';
+ }
+
+ @override
+ String quickPasteShortcutManual(String command) {
+ return '在桌面的键盘设置里添加一个自定义快捷键,命令填:$command';
+ }
+
+ @override
+ String get pickerSearch => '搜索';
+
+ @override
+ String get pickerPaste => '粘贴';
+
+ @override
+ String get pickerPlainText => '纯文本';
+
+ @override
+ String get pickerCopyOnly => '只复制';
+
+ @override
+ String get pickerUnfavoriteHint => '取消收藏(放回复制记录)';
+
+ @override
+ String pickerPasteManually(String key) {
+ return '选中后按 $key 粘贴';
+ }
+
+ @override
+ String get pickerGrantHint => '授予「辅助功能」权限后可直接粘贴';
+
+ @override
+ String get pickerDownloading => '正在下载,下完自动粘贴';
+
@override
String get imagePreviewTitle => '图片预览';
@@ -1128,6 +1330,9 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {
@override
String get navSettings => '設定';
+ @override
+ String get navFavorites => '收藏';
+
@override
String get linkConnecting => '正在連線…';
@@ -1293,6 +1498,9 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {
@override
String get filterFile => '檔案';
+ @override
+ String get filterLink => '連結';
+
@override
String get historyClearTooltip => '清除記錄';
@@ -1390,6 +1598,202 @@ class AppLocalizationsZhHantHk extends AppLocalizationsZh {
@override
String get searchEmptyBody => '搜尋範圍是複製過的文字和檔案名稱。';
+ @override
+ String get favoriteAction => '收藏';
+
+ @override
+ String get unfavoriteAction => '取消收藏';
+
+ @override
+ String get favoritedToast => '已收藏';
+
+ @override
+ String get unfavoritedToast => '已放回複製記錄';
+
+ @override
+ String get undo => '復原';
+
+ @override
+ String get favoriteSaving => '正在儲存…';
+
+ @override
+ String favoritedAt(String date) {
+ return '收藏於 $date';
+ }
+
+ @override
+ String favoritesSubtitle(int count, String size) {
+ return '$count 條 · 不會被自動清理 · 最多佔用 $size';
+ }
+
+ @override
+ String get favoritesEmptyTitle => '仍未有收藏';
+
+ @override
+ String get favoritesEmptyBody => '在複製記錄裏按星號,就會在這裏另存一份。收藏不會被自動清理。';
+
+ @override
+ String get favoritesSearchHint => '搜尋收藏';
+
+ @override
+ String favoriteLargeTitle(String size) {
+ return '另存一份 $size 的內容?';
+ }
+
+ @override
+ String favoriteLargeBody(String size, String device) {
+ return '收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用$device上 $size 的空間。';
+ }
+
+ @override
+ String get saveCopy => '另存';
+
+ @override
+ String clearKeepsFavorites(int count) {
+ return '已收藏的 $count 條會保留。';
+ }
+
+ @override
+ String get favoritesUsage => '收藏佔用';
+
+ @override
+ String get favoritesUsageDesc => '收藏不受上面兩項的限制,不會被自動清理';
+
+ @override
+ String upToSize(String size) {
+ return '最多 $size';
+ }
+
+ @override
+ String detailChars(int count) {
+ return '$count 字';
+ }
+
+ @override
+ String detailTruncated(int count) {
+ return '…… 共 $count 字';
+ }
+
+ @override
+ String detailMoreFiles(int count) {
+ return '還有 $count 個';
+ }
+
+ @override
+ String get detailReceiveFirst => '選取後先下載';
+
+ @override
+ String detailTotalSize(String size) {
+ return '共 $size';
+ }
+
+ @override
+ String get quickPaste => '快速貼上';
+
+ @override
+ String get quickPasteWindow => '快速貼上視窗';
+
+ @override
+ String get quickPasteWindowDesc => '在任何程式裏按快速鍵叫出複製記錄,選取即貼上';
+
+ @override
+ String get quickPasteShortcut => '快速鍵';
+
+ @override
+ String get quickPasteRecord => '按一下錄製';
+
+ @override
+ String get quickPasteRecording => '請按下新的快速鍵…';
+
+ @override
+ String get quickPasteUseDefault => '恢復預設';
+
+ @override
+ String get quickPasteNeedsModifier => '要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵';
+
+ @override
+ String get quickPasteNeedsModifierPc => '要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵';
+
+ @override
+ String get quickPasteAfterPick => '選取後';
+
+ @override
+ String get quickPastePasteIt => '直接貼上';
+
+ @override
+ String get quickPasteCopyIt => '只放入剪貼簿';
+
+ @override
+ String get quickPasteAccessibility => '輔助使用權限';
+
+ @override
+ String get quickPasteAccessibilityDesc => '直接貼上需要它;沒有授權時只放入剪貼簿,再由你按 ⌘V';
+
+ @override
+ String get quickPasteAllowed => '已授權';
+
+ @override
+ String get quickPasteAllow => '去授權';
+
+ @override
+ String get quickPasteNotRunning => '快速貼上視窗未有執行';
+
+ @override
+ String quickPasteInUse(String key) {
+ return '$key 已被其他程式佔用,請換一個組合';
+ }
+
+ @override
+ String quickPasteHotkeyFailed(String key, String detail) {
+ return '無法設定 $key:$detail';
+ }
+
+ @override
+ String get quickPastePortalKey => '在系統的快速鍵設定裏修改';
+
+ @override
+ String get quickPasteWaylandDesc =>
+ 'Wayland 下快速鍵要加在桌面的鍵盤設定裏;選取後放入剪貼簿,再按 Ctrl+V 貼上';
+
+ @override
+ String get quickPasteAddShortcut => '新增系統快速鍵';
+
+ @override
+ String quickPasteShortcutAdded(String key) {
+ return '已新增,按 $key 試試';
+ }
+
+ @override
+ String quickPasteShortcutManual(String command) {
+ return '在桌面的鍵盤設定裏新增一個自訂快速鍵,指令填:$command';
+ }
+
+ @override
+ String get pickerSearch => '搜尋';
+
+ @override
+ String get pickerPaste => '貼上';
+
+ @override
+ String get pickerPlainText => '純文字';
+
+ @override
+ String get pickerCopyOnly => '只複製';
+
+ @override
+ String get pickerUnfavoriteHint => '取消收藏(放回複製記錄)';
+
+ @override
+ String pickerPasteManually(String key) {
+ return '選取後按 $key 貼上';
+ }
+
+ @override
+ String get pickerGrantHint => '授予「輔助使用」權限後可直接貼上';
+
+ @override
+ String get pickerDownloading => '正在下載,下載完自動貼上';
+
@override
String get imagePreviewTitle => '圖片預覽';
@@ -2236,6 +2640,9 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {
@override
String get navSettings => '設定';
+ @override
+ String get navFavorites => '收藏';
+
@override
String get linkConnecting => '正在連線…';
@@ -2401,6 +2808,9 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {
@override
String get filterFile => '檔案';
+ @override
+ String get filterLink => '連結';
+
@override
String get historyClearTooltip => '清空記錄';
@@ -2498,6 +2908,202 @@ class AppLocalizationsZhHantTw extends AppLocalizationsZh {
@override
String get searchEmptyBody => '搜尋範圍是複製過的文字和檔名。';
+ @override
+ String get favoriteAction => '收藏';
+
+ @override
+ String get unfavoriteAction => '取消收藏';
+
+ @override
+ String get favoritedToast => '已收藏';
+
+ @override
+ String get unfavoritedToast => '已放回複製記錄';
+
+ @override
+ String get undo => '復原';
+
+ @override
+ String get favoriteSaving => '正在儲存…';
+
+ @override
+ String favoritedAt(String date) {
+ return '收藏於 $date';
+ }
+
+ @override
+ String favoritesSubtitle(int count, String size) {
+ return '$count 筆 · 不會被自動清除 · 最多佔用 $size';
+ }
+
+ @override
+ String get favoritesEmptyTitle => '還沒有收藏';
+
+ @override
+ String get favoritesEmptyBody => '在複製記錄裡點星號,就會在這裡另存一份。收藏不會被自動清除。';
+
+ @override
+ String get favoritesSearchHint => '搜尋收藏';
+
+ @override
+ String favoriteLargeTitle(String size) {
+ return '要另存一份 $size 的內容嗎?';
+ }
+
+ @override
+ String favoriteLargeBody(String size, String device) {
+ return '收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用$device上 $size 的空間。';
+ }
+
+ @override
+ String get saveCopy => '另存';
+
+ @override
+ String clearKeepsFavorites(int count) {
+ return '已收藏的 $count 筆會保留。';
+ }
+
+ @override
+ String get favoritesUsage => '收藏佔用';
+
+ @override
+ String get favoritesUsageDesc => '收藏不受上面兩項的限制,不會被自動清除';
+
+ @override
+ String upToSize(String size) {
+ return '最多 $size';
+ }
+
+ @override
+ String detailChars(int count) {
+ return '$count 字';
+ }
+
+ @override
+ String detailTruncated(int count) {
+ return '…… 共 $count 字';
+ }
+
+ @override
+ String detailMoreFiles(int count) {
+ return '還有 $count 個';
+ }
+
+ @override
+ String get detailReceiveFirst => '選取後先下載';
+
+ @override
+ String detailTotalSize(String size) {
+ return '共 $size';
+ }
+
+ @override
+ String get quickPaste => '快速貼上';
+
+ @override
+ String get quickPasteWindow => '快速貼上視窗';
+
+ @override
+ String get quickPasteWindowDesc => '在任何程式裡按快速鍵叫出複製記錄,選取即貼上';
+
+ @override
+ String get quickPasteShortcut => '快速鍵';
+
+ @override
+ String get quickPasteRecord => '按一下錄製';
+
+ @override
+ String get quickPasteRecording => '請按下新的快速鍵…';
+
+ @override
+ String get quickPasteUseDefault => '恢復預設';
+
+ @override
+ String get quickPasteNeedsModifier => '要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵';
+
+ @override
+ String get quickPasteNeedsModifierPc => '要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵';
+
+ @override
+ String get quickPasteAfterPick => '選取後';
+
+ @override
+ String get quickPastePasteIt => '直接貼上';
+
+ @override
+ String get quickPasteCopyIt => '只放進剪貼簿';
+
+ @override
+ String get quickPasteAccessibility => '輔助使用權限';
+
+ @override
+ String get quickPasteAccessibilityDesc => '直接貼上需要它;沒有授權時只放進剪貼簿,再由你按 ⌘V';
+
+ @override
+ String get quickPasteAllowed => '已授權';
+
+ @override
+ String get quickPasteAllow => '去授權';
+
+ @override
+ String get quickPasteNotRunning => '快速貼上視窗沒有在執行';
+
+ @override
+ String quickPasteInUse(String key) {
+ return '$key 已被其他程式佔用,請換一個組合';
+ }
+
+ @override
+ String quickPasteHotkeyFailed(String key, String detail) {
+ return '設定 $key 失敗:$detail';
+ }
+
+ @override
+ String get quickPastePortalKey => '在系統的快速鍵設定裡修改';
+
+ @override
+ String get quickPasteWaylandDesc =>
+ 'Wayland 下快速鍵要加在桌面的鍵盤設定裡;選取後放進剪貼簿,再按 Ctrl+V 貼上';
+
+ @override
+ String get quickPasteAddShortcut => '新增系統快速鍵';
+
+ @override
+ String quickPasteShortcutAdded(String key) {
+ return '已新增,按 $key 試試';
+ }
+
+ @override
+ String quickPasteShortcutManual(String command) {
+ return '在桌面的鍵盤設定裡新增一個自訂快速鍵,指令填:$command';
+ }
+
+ @override
+ String get pickerSearch => '搜尋';
+
+ @override
+ String get pickerPaste => '貼上';
+
+ @override
+ String get pickerPlainText => '純文字';
+
+ @override
+ String get pickerCopyOnly => '只複製';
+
+ @override
+ String get pickerUnfavoriteHint => '取消收藏(放回複製記錄)';
+
+ @override
+ String pickerPasteManually(String key) {
+ return '選取後按 $key 貼上';
+ }
+
+ @override
+ String get pickerGrantHint => '授予「輔助使用」權限後可直接貼上';
+
+ @override
+ String get pickerDownloading => '正在下載,下載完自動貼上';
+
@override
String get imagePreviewTitle => '圖片預覽';
diff --git a/ui/lib/l10n/app_zh.arb b/ui/lib/l10n/app_zh.arb
index c72ba5e..bef54ef 100644
--- a/ui/lib/l10n/app_zh.arb
+++ b/ui/lib/l10n/app_zh.arb
@@ -4,6 +4,7 @@
"navHistory": "复制记录",
"navDevices": "设备",
"navSettings": "设置",
+ "navFavorites": "收藏",
"linkConnecting": "正在连接…",
"linkServiceNotRunning": "后台服务未运行",
"linkLanMode": "在局域网中查找设备",
@@ -49,6 +50,7 @@
"filterText": "文本",
"filterImage": "图片",
"filterFile": "文件",
+ "filterLink": "链接",
"historyClearTooltip": "清空记录",
"historyEmptyTitle": "还没有记录",
"historyEmptyFilteredTitle": "没有这一类的记录",
@@ -78,6 +80,61 @@
"searchResultCount": "找到 {count} 条",
"searchEmptyTitle": "没有找到「{query}」",
"searchEmptyBody": "搜索的是复制过的文字和文件名。",
+ "favoriteAction": "收藏",
+ "unfavoriteAction": "取消收藏",
+ "favoritedToast": "已收藏",
+ "unfavoritedToast": "已放回复制记录",
+ "undo": "撤销",
+ "favoriteSaving": "正在保存…",
+ "favoritedAt": "收藏于 {date}",
+ "favoritesSubtitle": "{count} 条 · 不会被自动清理 · 最多占用 {size}",
+ "favoritesEmptyTitle": "还没有收藏",
+ "favoritesEmptyBody": "在复制记录里点星标,就会在这里另存一份。收藏不会被自动清理。",
+ "favoritesSearchHint": "搜索收藏",
+ "favoriteLargeTitle": "另存一份 {size} 的内容?",
+ "favoriteLargeBody": "收藏会另存一份,原文件之后改动或删除都不影响收藏。这会占用{device}上 {size} 的空间。",
+ "saveCopy": "另存",
+ "clearKeepsFavorites": "已收藏的 {count} 条会保留。",
+ "favoritesUsage": "收藏占用",
+ "favoritesUsageDesc": "收藏不受上面两项的限制,不会被自动清理",
+ "upToSize": "最多 {size}",
+ "detailChars": "{count} 字",
+ "detailTruncated": "…… 共 {count} 字",
+ "detailMoreFiles": "还有 {count} 个",
+ "detailReceiveFirst": "选中后先下载",
+ "detailTotalSize": "共 {size}",
+ "quickPaste": "快捷粘贴",
+ "quickPasteWindow": "快捷粘贴窗口",
+ "quickPasteWindowDesc": "在任何程序里按快捷键呼出复制记录,选中即粘贴",
+ "quickPasteShortcut": "快捷键",
+ "quickPasteRecord": "点击录制",
+ "quickPasteRecording": "请按下新的快捷键…",
+ "quickPasteUseDefault": "恢复默认",
+ "quickPasteNeedsModifier": "要带上 ⌃、⌥、⇧ 或 ⌘,或者用功能键",
+ "quickPasteNeedsModifierPc": "要带上 Ctrl、Alt、Shift 或 Win 键,或者用功能键",
+ "quickPasteAfterPick": "选中后",
+ "quickPastePasteIt": "直接粘贴",
+ "quickPasteCopyIt": "只放进剪贴板",
+ "quickPasteAccessibility": "辅助功能权限",
+ "quickPasteAccessibilityDesc": "直接粘贴需要它;没有授权时只放进剪贴板,再由你按 ⌘V",
+ "quickPasteAllowed": "已授权",
+ "quickPasteAllow": "去授权",
+ "quickPasteNotRunning": "快捷粘贴窗口没有运行",
+ "quickPasteInUse": "{key} 已被其他程序占用,换一个组合",
+ "quickPasteHotkeyFailed": "设置 {key} 失败:{detail}",
+ "quickPastePortalKey": "在系统的快捷键设置里修改",
+ "quickPasteWaylandDesc": "Wayland 下快捷键要加在桌面的键盘设置里;选中后放进剪贴板,再按 Ctrl+V 粘贴",
+ "quickPasteAddShortcut": "添加系统快捷键",
+ "quickPasteShortcutAdded": "已添加,按 {key} 试试",
+ "quickPasteShortcutManual": "在桌面的键盘设置里添加一个自定义快捷键,命令填:{command}",
+ "pickerSearch": "搜索",
+ "pickerPaste": "粘贴",
+ "pickerPlainText": "纯文本",
+ "pickerCopyOnly": "只复制",
+ "pickerUnfavoriteHint": "取消收藏(放回复制记录)",
+ "pickerPasteManually": "选中后按 {key} 粘贴",
+ "pickerGrantHint": "授予「辅助功能」权限后可直接粘贴",
+ "pickerDownloading": "正在下载,下完自动粘贴",
"imagePreviewTitle": "图片预览",
"closePreview": "关闭预览",
"previousImage": "上一张",
diff --git a/ui/lib/l10n/app_zh_Hant_HK.arb b/ui/lib/l10n/app_zh_Hant_HK.arb
index dd7eeab..daac198 100644
--- a/ui/lib/l10n/app_zh_Hant_HK.arb
+++ b/ui/lib/l10n/app_zh_Hant_HK.arb
@@ -4,6 +4,7 @@
"navHistory": "複製記錄",
"navDevices": "裝置",
"navSettings": "設定",
+ "navFavorites": "收藏",
"linkConnecting": "正在連線…",
"linkServiceNotRunning": "背景服務未在執行",
"linkLanMode": "在區域網絡中尋找裝置",
@@ -49,6 +50,7 @@
"filterText": "文字",
"filterImage": "圖片",
"filterFile": "檔案",
+ "filterLink": "連結",
"historyClearTooltip": "清除記錄",
"historyEmptyTitle": "仍未有記錄",
"historyEmptyFilteredTitle": "沒有這一類的記錄",
@@ -78,6 +80,61 @@
"searchResultCount": "找到 {count} 條",
"searchEmptyTitle": "找不到「{query}」",
"searchEmptyBody": "搜尋範圍是複製過的文字和檔案名稱。",
+ "favoriteAction": "收藏",
+ "unfavoriteAction": "取消收藏",
+ "favoritedToast": "已收藏",
+ "unfavoritedToast": "已放回複製記錄",
+ "undo": "復原",
+ "favoriteSaving": "正在儲存…",
+ "favoritedAt": "收藏於 {date}",
+ "favoritesSubtitle": "{count} 條 · 不會被自動清理 · 最多佔用 {size}",
+ "favoritesEmptyTitle": "仍未有收藏",
+ "favoritesEmptyBody": "在複製記錄裏按星號,就會在這裏另存一份。收藏不會被自動清理。",
+ "favoritesSearchHint": "搜尋收藏",
+ "favoriteLargeTitle": "另存一份 {size} 的內容?",
+ "favoriteLargeBody": "收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用{device}上 {size} 的空間。",
+ "saveCopy": "另存",
+ "clearKeepsFavorites": "已收藏的 {count} 條會保留。",
+ "favoritesUsage": "收藏佔用",
+ "favoritesUsageDesc": "收藏不受上面兩項的限制,不會被自動清理",
+ "upToSize": "最多 {size}",
+ "detailChars": "{count} 字",
+ "detailTruncated": "…… 共 {count} 字",
+ "detailMoreFiles": "還有 {count} 個",
+ "detailReceiveFirst": "選取後先下載",
+ "detailTotalSize": "共 {size}",
+ "quickPaste": "快速貼上",
+ "quickPasteWindow": "快速貼上視窗",
+ "quickPasteWindowDesc": "在任何程式裏按快速鍵叫出複製記錄,選取即貼上",
+ "quickPasteShortcut": "快速鍵",
+ "quickPasteRecord": "按一下錄製",
+ "quickPasteRecording": "請按下新的快速鍵…",
+ "quickPasteUseDefault": "恢復預設",
+ "quickPasteNeedsModifier": "要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵",
+ "quickPasteNeedsModifierPc": "要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵",
+ "quickPasteAfterPick": "選取後",
+ "quickPastePasteIt": "直接貼上",
+ "quickPasteCopyIt": "只放入剪貼簿",
+ "quickPasteAccessibility": "輔助使用權限",
+ "quickPasteAccessibilityDesc": "直接貼上需要它;沒有授權時只放入剪貼簿,再由你按 ⌘V",
+ "quickPasteAllowed": "已授權",
+ "quickPasteAllow": "去授權",
+ "quickPasteNotRunning": "快速貼上視窗未有執行",
+ "quickPasteInUse": "{key} 已被其他程式佔用,請換一個組合",
+ "quickPasteHotkeyFailed": "無法設定 {key}:{detail}",
+ "quickPastePortalKey": "在系統的快速鍵設定裏修改",
+ "quickPasteWaylandDesc": "Wayland 下快速鍵要加在桌面的鍵盤設定裏;選取後放入剪貼簿,再按 Ctrl+V 貼上",
+ "quickPasteAddShortcut": "新增系統快速鍵",
+ "quickPasteShortcutAdded": "已新增,按 {key} 試試",
+ "quickPasteShortcutManual": "在桌面的鍵盤設定裏新增一個自訂快速鍵,指令填:{command}",
+ "pickerSearch": "搜尋",
+ "pickerPaste": "貼上",
+ "pickerPlainText": "純文字",
+ "pickerCopyOnly": "只複製",
+ "pickerUnfavoriteHint": "取消收藏(放回複製記錄)",
+ "pickerPasteManually": "選取後按 {key} 貼上",
+ "pickerGrantHint": "授予「輔助使用」權限後可直接貼上",
+ "pickerDownloading": "正在下載,下載完自動貼上",
"imagePreviewTitle": "圖片預覽",
"closePreview": "關閉預覽",
"previousImage": "上一張",
diff --git a/ui/lib/l10n/app_zh_Hant_TW.arb b/ui/lib/l10n/app_zh_Hant_TW.arb
index da8fb1b..7efa9e8 100644
--- a/ui/lib/l10n/app_zh_Hant_TW.arb
+++ b/ui/lib/l10n/app_zh_Hant_TW.arb
@@ -4,6 +4,7 @@
"navHistory": "複製記錄",
"navDevices": "裝置",
"navSettings": "設定",
+ "navFavorites": "收藏",
"linkConnecting": "正在連線…",
"linkServiceNotRunning": "背景服務未執行",
"linkLanMode": "在區域網路中尋找裝置",
@@ -49,6 +50,7 @@
"filterText": "文字",
"filterImage": "圖片",
"filterFile": "檔案",
+ "filterLink": "連結",
"historyClearTooltip": "清空記錄",
"historyEmptyTitle": "還沒有記錄",
"historyEmptyFilteredTitle": "沒有這一類的記錄",
@@ -78,6 +80,61 @@
"searchResultCount": "找到 {count} 筆",
"searchEmptyTitle": "找不到「{query}」",
"searchEmptyBody": "搜尋範圍是複製過的文字和檔名。",
+ "favoriteAction": "收藏",
+ "unfavoriteAction": "取消收藏",
+ "favoritedToast": "已收藏",
+ "unfavoritedToast": "已放回複製記錄",
+ "undo": "復原",
+ "favoriteSaving": "正在儲存…",
+ "favoritedAt": "收藏於 {date}",
+ "favoritesSubtitle": "{count} 筆 · 不會被自動清除 · 最多佔用 {size}",
+ "favoritesEmptyTitle": "還沒有收藏",
+ "favoritesEmptyBody": "在複製記錄裡點星號,就會在這裡另存一份。收藏不會被自動清除。",
+ "favoritesSearchHint": "搜尋收藏",
+ "favoriteLargeTitle": "要另存一份 {size} 的內容嗎?",
+ "favoriteLargeBody": "收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用{device}上 {size} 的空間。",
+ "saveCopy": "另存",
+ "clearKeepsFavorites": "已收藏的 {count} 筆會保留。",
+ "favoritesUsage": "收藏佔用",
+ "favoritesUsageDesc": "收藏不受上面兩項的限制,不會被自動清除",
+ "upToSize": "最多 {size}",
+ "detailChars": "{count} 字",
+ "detailTruncated": "…… 共 {count} 字",
+ "detailMoreFiles": "還有 {count} 個",
+ "detailReceiveFirst": "選取後先下載",
+ "detailTotalSize": "共 {size}",
+ "quickPaste": "快速貼上",
+ "quickPasteWindow": "快速貼上視窗",
+ "quickPasteWindowDesc": "在任何程式裡按快速鍵叫出複製記錄,選取即貼上",
+ "quickPasteShortcut": "快速鍵",
+ "quickPasteRecord": "按一下錄製",
+ "quickPasteRecording": "請按下新的快速鍵…",
+ "quickPasteUseDefault": "恢復預設",
+ "quickPasteNeedsModifier": "要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵",
+ "quickPasteNeedsModifierPc": "要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵",
+ "quickPasteAfterPick": "選取後",
+ "quickPastePasteIt": "直接貼上",
+ "quickPasteCopyIt": "只放進剪貼簿",
+ "quickPasteAccessibility": "輔助使用權限",
+ "quickPasteAccessibilityDesc": "直接貼上需要它;沒有授權時只放進剪貼簿,再由你按 ⌘V",
+ "quickPasteAllowed": "已授權",
+ "quickPasteAllow": "去授權",
+ "quickPasteNotRunning": "快速貼上視窗沒有在執行",
+ "quickPasteInUse": "{key} 已被其他程式佔用,請換一個組合",
+ "quickPasteHotkeyFailed": "設定 {key} 失敗:{detail}",
+ "quickPastePortalKey": "在系統的快速鍵設定裡修改",
+ "quickPasteWaylandDesc": "Wayland 下快速鍵要加在桌面的鍵盤設定裡;選取後放進剪貼簿,再按 Ctrl+V 貼上",
+ "quickPasteAddShortcut": "新增系統快速鍵",
+ "quickPasteShortcutAdded": "已新增,按 {key} 試試",
+ "quickPasteShortcutManual": "在桌面的鍵盤設定裡新增一個自訂快速鍵,指令填:{command}",
+ "pickerSearch": "搜尋",
+ "pickerPaste": "貼上",
+ "pickerPlainText": "純文字",
+ "pickerCopyOnly": "只複製",
+ "pickerUnfavoriteHint": "取消收藏(放回複製記錄)",
+ "pickerPasteManually": "選取後按 {key} 貼上",
+ "pickerGrantHint": "授予「輔助使用」權限後可直接貼上",
+ "pickerDownloading": "正在下載,下載完自動貼上",
"imagePreviewTitle": "圖片預覽",
"closePreview": "關閉預覽",
"previousImage": "上一張",
diff --git a/ui/lib/main.dart b/ui/lib/main.dart
index 36cfec4..547d071 100644
--- a/ui/lib/main.dart
+++ b/ui/lib/main.dart
@@ -6,17 +6,26 @@ import 'app_state.dart';
import 'background_service.dart';
import 'i18n.dart';
import 'pages/devices_page.dart';
+import 'pages/favorites_page.dart';
import 'pages/history_page.dart';
import 'pages/service_page.dart';
import 'pages/settings_page.dart';
import 'pages/official_service_page.dart';
+import 'picker/picker_main.dart';
import 'theme.dart';
import 'widgets/common.dart';
import 'widgets/pairing_dialog.dart';
import 'widgets/update_dialog.dart';
import 'icons.dart';
-void main() => runApp(const PasteFerryApp());
+/// 带 --picker 启动的是快捷粘贴窗口进程,见 picker/picker_main.dart。
+void main(List<String> args) {
+ if (args.contains('--picker')) {
+ runPicker();
+ return;
+ }
+ runApp(const PasteFerryApp());
+}
class PasteFerryApp extends StatefulWidget {
const PasteFerryApp({super.key, this.state});
@@ -110,7 +119,7 @@ class AppScope extends InheritedNotifier<AppState> {
context.getInheritedWidgetOfExactType<AppScope>()!.notifier!;
}
-enum Section { history, devices, official, settings }
+enum Section { history, favorites, devices, official, settings }
class Shell extends StatefulWidget {
const Shell({super.key, this.initialSection = Section.history});
@@ -271,6 +280,7 @@ class _ShellState extends State<Shell> with WidgetsBindingObserver {
? const ServicePage()
: switch (_section) {
Section.history => const HistoryPage(),
+ Section.favorites => const FavoritesPage(),
Section.devices => const DevicesPage(),
Section.official => const OfficialServicePage(),
Section.settings => const SettingsPage(),
@@ -328,6 +338,13 @@ class _Sidebar extends StatelessWidget {
trailing: state.records.isEmpty ? null : '${state.records.length}',
onTap: () => onSelect(Section.history),
),
+ _NavItem(
+ icon: AppIcons.star,
+ label: l.navFavorites,
+ selected: current == Section.favorites,
+ trailing: state.favorites.isEmpty ? null : '${state.favorites.length}',
+ onTap: () => onSelect(Section.favorites),
+ ),
_NavItem(
icon: AppIcons.deviceLaptop,
label: l.navDevices,
diff --git a/ui/lib/pages/favorites_page.dart b/ui/lib/pages/favorites_page.dart
new file mode 100644
index 0000000..84380f0
--- /dev/null
+++ b/ui/lib/pages/favorites_page.dart
@@ -0,0 +1,303 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../app_state.dart';
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../i18n.dart';
+import '../icons.dart';
+import '../main.dart';
+import '../records.dart';
+import '../theme.dart';
+import '../widgets/common.dart';
+import '../widgets/favorite_actions.dart';
+import '../widgets/image_preview_dialog.dart';
+import '../widgets/record_hover.dart';
+
+/// 收藏:另存的一份,不会被自动清理。见 design/quick-paste-and-favorites.md 第 3 节。
+///
+/// 布局与复制记录页一样。每一行只有两个操作:放进剪贴板、取消收藏(放回复制记录,可以撤销)。
+/// 没有删除:想删掉的先取消收藏,再到复制记录里删。
+class FavoritesPage extends StatefulWidget {
+ const FavoritesPage({super.key});
+
+ @override
+ State<FavoritesPage> createState() => _FavoritesPageState();
+}
+
+class _FavoritesPageState extends State<FavoritesPage> {
+ RecordFilter _filter = RecordFilter.all;
+ final _search = TextEditingController();
+ final _searchFocus = FocusNode();
+ AppState? _state;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _state = AppScope.read(context);
+ }
+
+ @override
+ void dispose() {
+ // 离开这一页就不再搜索,回来看到的是完整的列表
+ _state?.searchFavorites('', notify: false);
+ _search.dispose();
+ _searchFocus.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final state = AppScope.of(context);
+ final searching = state.searchingFavorites;
+ final all = state.favorites;
+ // 搜索结果还没回来时为 null,这时列表先空着,不闪一下「没有找到」
+ final records = (searching ? state.favoriteResults : all)?.where(_filter.matches).toList();
+ final l = context.l10n;
+
+ final page = Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ PageHeader(
+ title: l.navFavorites,
+ subtitle: searching && records != null
+ ? l.searchResultCount(records.length)
+ : all.isEmpty
+ ? null
+ : l.favoritesSubtitle(all.length, humanBytes(state.favoritesBytes)),
+ ),
+ if (all.isNotEmpty || searching)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.md),
+ child: Row(
+ children: [
+ Expanded(
+ child: SearchField(
+ controller: _search,
+ focusNode: _searchFocus,
+ hint: l.favoritesSearchHint,
+ clearTooltip: l.searchClear,
+ onChanged: state.searchFavorites,
+ ),
+ ),
+ const SizedBox(width: Insets.md),
+ Segmented<RecordFilter>(
+ value: _filter,
+ segments: [for (final f in RecordFilter.values) (f, f.label(l))],
+ onChanged: (f) => setState(() => _filter = f),
+ ),
+ ],
+ ),
+ ),
+ Expanded(
+ child: records == null
+ ? const SizedBox.shrink()
+ : records.isEmpty && searching
+ ? EmptyState(
+ icon: AppIcons.search,
+ title: l.searchEmptyTitle(state.favoriteQuery),
+ description: l.searchEmptyBody,
+ )
+ : records.isEmpty
+ ? EmptyState(
+ icon: all.isEmpty ? AppIcons.star : AppIcons.filter,
+ title: all.isEmpty ? l.favoritesEmptyTitle : l.historyEmptyFilteredTitle,
+ description: all.isEmpty ? l.favoritesEmptyBody : null,
+ )
+ : CustomScrollView(
+ slivers: [
+ SliverPadding(
+ padding: const EdgeInsets.fromLTRB(Insets.xl, 0, Insets.xl, Insets.xl),
+ sliver: DecoratedSliver(
+ decoration: BoxDecoration(
+ color: context.palette.surface,
+ borderRadius: BorderRadius.circular(Radii.md),
+ border: Border.all(color: context.palette.border),
+ ),
+ sliver: SliverPadding(
+ padding: const EdgeInsets.all(Insets.xs),
+ sliver: SliverList.separated(
+ itemCount: records.length,
+ separatorBuilder: (_, _) => const Divider(indent: 44, endIndent: 8),
+ itemBuilder: (_, i) => _FavoriteRow(
+ key: ValueKey(records[i].id),
+ record: records[i],
+ highlight: searching ? state.favoriteQuery : null,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+
+ // ⌘F(Windows、Linux 上是 Ctrl+F)跳到搜索框
+ return CallbackShortcuts(
+ bindings: {
+ SingleActivator(LogicalKeyboardKey.keyF, meta: Platform.isMacOS, control: !Platform.isMacOS):
+ _searchFocus.requestFocus,
+ },
+ child: Focus(autofocus: true, child: page),
+ );
+ }
+}
+
+class _FavoriteRow extends StatefulWidget {
+ const _FavoriteRow({super.key, required this.record, this.highlight});
+
+ final ClipRecord record;
+ final String? highlight;
+
+ @override
+ State<_FavoriteRow> createState() => _FavoriteRowState();
+}
+
+class _FavoriteRowState extends State<_FavoriteRow> {
+ bool _hovered = false;
+ bool _busy = false;
+
+ @override
+ Widget build(BuildContext context) =>
+ RecordHover(record: widget.record, details: AppScope.read(context), child: _content(context));
+
+ Widget _content(BuildContext context) {
+ final r = widget.record;
+ final p = context.palette;
+ final l = context.l10n;
+ final previewable = r.imageCount > 0 && r.status == ClipStatus.CLIP_STATUS_READY;
+ final detail = switch (r.status) {
+ ClipStatus.CLIP_STATUS_FETCHING => l.favoriteSaving,
+ ClipStatus.CLIP_STATUS_FAILED => r.error.isEmpty ? l.transferFailed : r.error,
+ _ => null,
+ };
+
+ return MouseRegion(
+ cursor: previewable ? SystemMouseCursors.click : MouseCursor.defer,
+ onEnter: (_) => setState(() => _hovered = true),
+ onExit: (_) => setState(() => _hovered = false),
+ child: InkWell(
+ onTap: previewable ? () => showImagePreview(context, r.id) : null,
+ borderRadius: BorderRadius.circular(Radii.sm),
+ child: Container(
+ constraints: const BoxConstraints(minHeight: 52),
+ padding: const EdgeInsets.symmetric(horizontal: Insets.md, vertical: Insets.sm),
+ decoration: BoxDecoration(
+ color: _hovered ? p.hover : Colors.transparent,
+ borderRadius: BorderRadius.circular(Radii.sm),
+ ),
+ child: Row(
+ children: [
+ Icon(kindIcon(r), size: 18, color: p.textDim),
+ const SizedBox(width: Insets.md),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text.rich(
+ TextSpan(
+ children: highlightMatches(
+ recordTitle(r, query: widget.highlight),
+ widget.highlight,
+ TextStyle(backgroundColor: p.accent.withValues(alpha: 0.28)),
+ ),
+ ),
+ style: context.text.labelLarge,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ const SizedBox(height: 2),
+ Text(recordMeta(r), style: context.text.bodySmall, maxLines: 1, overflow: TextOverflow.ellipsis),
+ if (detail != null) ...[
+ const SizedBox(height: 2),
+ Text(
+ detail,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: context.text.bodySmall?.copyWith(
+ color: r.status == ClipStatus.CLIP_STATUS_FAILED ? p.danger : p.textDim,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ const SizedBox(width: Insets.md),
+ _trailing(context, r),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _trailing(BuildContext context, ClipRecord r) {
+ final l = context.l10n;
+ if (_busy) {
+ return const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2));
+ }
+ final unfavorite = IconAction(
+ icon: AppIcons.starFill,
+ color: context.palette.accent,
+ tooltip: l.unfavoriteAction,
+ onTap: () => toggleFavorite(context, AppScope.read(context), r),
+ );
+ switch (r.status) {
+ case ClipStatus.CLIP_STATUS_FETCHING:
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const SizedBox(width: 72, child: LinearProgressIndicator(minHeight: 3)),
+ const SizedBox(width: Insets.sm),
+ unfavorite,
+ ],
+ );
+ case ClipStatus.CLIP_STATUS_FAILED:
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ OutlinedButton(
+ // 再收藏一次就是重新另存:下载失败的重新下载,复制失败的重新复制
+ onPressed: () => _run(() => AppScope.read(context).setFavorite(r.id, true), null),
+ child: Text(l.retry),
+ ),
+ const SizedBox(width: Insets.xs),
+ unfavorite,
+ ],
+ );
+ default:
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Visibility(
+ visible: _hovered,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: TextButton(
+ onPressed: () => _run(() => AppScope.read(context).applyToClipboard(r.id), l.putOnClipboardDone),
+ child: Text(l.putOnClipboard),
+ ),
+ ),
+ unfavorite,
+ ],
+ );
+ }
+ }
+
+ Future<void> _run(Future<void> Function() action, String? success) async {
+ setState(() => _busy = true);
+ try {
+ await action();
+ if (mounted && success != null) showToast(context, success);
+ } catch (e) {
+ if (mounted) showToast(context, AppState.describeError(e), error: true);
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+}
diff --git a/ui/lib/pages/history_page.dart b/ui/lib/pages/history_page.dart
index 85c189a..03a0bac 100644
--- a/ui/lib/pages/history_page.dart
+++ b/ui/lib/pages/history_page.dart
@@ -7,13 +7,16 @@ import '../app_state.dart';
import '../gen/pasteferry/v1/daemon.pb.dart';
import '../i18n.dart';
import '../main.dart';
+import '../records.dart';
import '../theme.dart';
import '../widgets/common.dart';
+import '../widgets/favorite_actions.dart';
import '../widgets/image_preview_dialog.dart';
+import '../widgets/record_hover.dart';
import '../icons.dart';
import '../platform.dart';
-enum _Filter { all, text, image, file }
+export '../records.dart' show kindIcon, recordTitle, highlightMatches;
class HistoryPage extends StatefulWidget {
const HistoryPage({super.key});
@@ -23,7 +26,7 @@ class HistoryPage extends StatefulWidget {
}
class _HistoryPageState extends State<HistoryPage> {
- _Filter _filter = _Filter.all;
+ RecordFilter _filter = RecordFilter.all;
final _search = TextEditingController();
final _searchFocus = FocusNode();
AppState? _state;
@@ -43,14 +46,7 @@ class _HistoryPageState extends State<HistoryPage> {
super.dispose();
}
- bool _matches(ClipRecord r) => switch (_filter) {
- _Filter.all => true,
- // 富文本也是文字,用户不关心它在剪贴板里是不是 HTML
- _Filter.text =>
- r.kind == ClipKind.CLIP_KIND_TEXT || r.kind == ClipKind.CLIP_KIND_HTML,
- _Filter.image => r.kind == ClipKind.CLIP_KIND_IMAGE,
- _Filter.file => r.kind == ClipKind.CLIP_KIND_FILE,
- };
+ bool _matches(ClipRecord r) => _filter.matches(r);
@override
Widget build(BuildContext context) {
@@ -101,14 +97,9 @@ class _HistoryPageState extends State<HistoryPage> {
),
),
const SizedBox(width: Insets.md),
- Segmented<_Filter>(
+ Segmented<RecordFilter>(
value: _filter,
- segments: [
- (_Filter.all, l.filterAll),
- (_Filter.text, l.filterText),
- (_Filter.image, l.filterImage),
- (_Filter.file, l.filterFile),
- ],
+ segments: [for (final f in RecordFilter.values) (f, f.label(l))],
onChanged: (f) => setState(() => _filter = f),
),
],
@@ -130,11 +121,11 @@ class _HistoryPageState extends State<HistoryPage> {
)
: records.isEmpty
? EmptyState(
- icon: _filter == _Filter.all
+ icon: _filter == RecordFilter.all
? AppIcons.docOnClipboard
: AppIcons.filter,
- title: _filter == _Filter.all ? l.historyEmptyTitle : l.historyEmptyFilteredTitle,
- description: _filter == _Filter.all
+ title: _filter == RecordFilter.all ? l.historyEmptyTitle : l.historyEmptyFilteredTitle,
+ description: _filter == RecordFilter.all
? l.historyEmptyBody
: null,
)
@@ -186,7 +177,11 @@ class _HistoryPageState extends State<HistoryPage> {
context: context,
builder: (ctx) => AlertDialog(
title: Text(l.clearConfirmTitle),
- content: Text(l.clearConfirmBody(Wording.thisDeviceInText)),
+ content: Text([
+ l.clearConfirmBody(Wording.thisDeviceInText),
+ // 清空不影响收藏,说一声免得用户以为收藏也没了
+ if (state.favorites.isNotEmpty) l.clearKeepsFavorites(state.favorites.length),
+ ].join('\n\n')),
actions: [
OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
FilledButton(
@@ -250,8 +245,12 @@ class _RecordRowState extends State<_RecordRow> {
bool _hovered = false;
bool _busy = false;
+ // 鼠标停一会儿弹出完整内容,见 widgets/record_hover.dart
@override
- Widget build(BuildContext context) {
+ Widget build(BuildContext context) =>
+ RecordHover(record: widget.record, details: AppScope.read(context), child: _content(context));
+
+ Widget _content(BuildContext context) {
final r = widget.record;
final p = context.palette;
// 剪贴板里的图片、以及复制的图片文件,点一下这一行就能预览,不另放按钮
@@ -307,11 +306,7 @@ class _RecordRowState extends State<_RecordRow> {
),
const SizedBox(height: 2),
Text(
- [
- r.outgoing ? context.l10n.thisDeviceShort : context.l10n.fromDevice(r.originDeviceName),
- if (r.totalSize > 0) humanBytes(r.totalSize.toInt()),
- relativeTime(DateTime.fromMillisecondsSinceEpoch(r.createdAtUnix.toInt() * 1000)),
- ].join(' · '),
+ recordMeta(r),
style: context.text.bodySmall,
maxLines: 1,
overflow: TextOverflow.ellipsis,
@@ -338,6 +333,23 @@ class _RecordRowState extends State<_RecordRow> {
);
}
+ /// 星标:已收藏的一直亮着,没收藏的悬停时才出现。
+ Widget _star(BuildContext context, ClipRecord r) {
+ final l = context.l10n;
+ return Visibility(
+ visible: _hovered || r.favorited,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: IconAction(
+ icon: r.favorited ? AppIcons.starFill : AppIcons.star,
+ color: r.favorited ? context.palette.accent : null,
+ tooltip: r.favorited ? l.unfavoriteAction : l.favoriteAction,
+ onTap: () => toggleFavorite(context, AppScope.read(context), r),
+ ),
+ );
+ }
+
Widget _trailing(BuildContext context, ClipRecord r) {
final p = context.palette;
final l = context.l10n;
@@ -350,10 +362,17 @@ class _RecordRowState extends State<_RecordRow> {
}
switch (r.status) {
case ClipStatus.CLIP_STATUS_REMOTE_ONLY:
- // 超过自动同步阈值的大文件:只有元数据,需要时再拉
- return OutlinedButton(
- onPressed: () => _run(() => AppScope.read(context).fetch(r.id), l.fetchStarted),
- child: Text(l.fetch),
+ // 超过自动同步阈值的大文件:只有元数据,需要时再拉。收藏它也会先下载
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _star(context, r),
+ const SizedBox(width: Insets.xs),
+ OutlinedButton(
+ onPressed: () => _run(() => AppScope.read(context).fetch(r.id), l.fetchStarted),
+ child: Text(l.fetch),
+ ),
+ ],
);
case ClipStatus.CLIP_STATUS_FETCHING:
// 知道总量时显示真实进度,否则显示不确定进度
@@ -388,6 +407,7 @@ class _RecordRowState extends State<_RecordRow> {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
+ _star(context, r),
hoverOnly(TextButton(
onPressed: () =>
_run(() => AppScope.read(context).applyToClipboard(r.id), l.putOnClipboardDone),
@@ -416,48 +436,3 @@ class _RecordRowState extends State<_RecordRow> {
}
}
-/// 按内容类型区分的图标:只靠形状区分,不靠颜色。
-IconData kindIcon(ClipRecord r) => switch (r.kind) {
- ClipKind.CLIP_KIND_TEXT => AppIcons.textAlignLeft,
- ClipKind.CLIP_KIND_HTML => AppIcons.docRichtext,
- ClipKind.CLIP_KIND_IMAGE => AppIcons.photo,
- // 单张图片文件也用图片图标,一眼看出点开能预览
- ClipKind.CLIP_KIND_FILE when r.items.length == 1 && r.imageCount == 1 => AppIcons.photo,
- ClipKind.CLIP_KIND_FILE when r.items.length > 1 => AppIcons.docOnDoc,
- ClipKind.CLIP_KIND_FILE when r.items.isNotEmpty && r.items.first.isDir =>
- AppIcons.folder,
- ClipKind.CLIP_KIND_FILE => AppIcons.doc,
- _ => AppIcons.questionCircle,
- };
-
-/// 记录在列表里的标题。搜索时传入 [query]:一次复制了多个文件、搜到的又不是第一个时,
-/// 标题改用搜到的那个文件名打头,看得出为什么搜到了它。
-String recordTitle(ClipRecord r, {String? query}) {
- // 图片和文件的标题按当前界面语言拼:后台服务存下的摘要是写入时的中文,不会跟着换语言
- if (r.kind == ClipKind.CLIP_KIND_IMAGE) return appL10n.imageRecord;
- if (r.kind != ClipKind.CLIP_KIND_FILE && r.textPreview.isNotEmpty) {
- return r.textPreview.replaceAll('\n', ' ').trim();
- }
- if (r.items.isEmpty) return appL10n.emptyRecord;
- if (r.items.length == 1) return r.items.first.name;
- final q = query?.toLowerCase();
- final lead = q == null ? null : r.items.where((i) => i.name.toLowerCase().contains(q)).firstOrNull;
- return appL10n.itemsSummary((lead ?? r.items.first).name, r.items.length - 1, r.items.length);
-}
-
-/// 把 [text] 里所有不分大小写匹配 [query] 的片段套上 [mark] 样式。
-/// 转小写后长度变了的少数字符(如土耳其语的 İ)对不上位置,这时不标。
-List<TextSpan> highlightMatches(String text, String? query, TextStyle mark) {
- final lower = text.toLowerCase();
- final q = query?.toLowerCase() ?? '';
- if (q.isEmpty || lower.length != text.length) return [TextSpan(text: text)];
- final spans = <TextSpan>[];
- var start = 0;
- for (var i = lower.indexOf(q); i >= 0; i = lower.indexOf(q, start)) {
- if (i > start) spans.add(TextSpan(text: text.substring(start, i)));
- spans.add(TextSpan(text: text.substring(i, i + q.length), style: mark));
- start = i + q.length;
- }
- if (start < text.length) spans.add(TextSpan(text: text.substring(start)));
- return spans;
-}
diff --git a/ui/lib/pages/quick_paste_settings.dart b/ui/lib/pages/quick_paste_settings.dart
new file mode 100644
index 0000000..95d7742
--- /dev/null
+++ b/ui/lib/pages/quick_paste_settings.dart
@@ -0,0 +1,267 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../app_state.dart';
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../hotkey.dart';
+import '../i18n.dart';
+import '../main.dart';
+import '../quick_paste_service.dart';
+import '../theme.dart';
+import '../widgets/common.dart';
+
+/// 设置页的「快捷粘贴」一节:开关、快捷键、选中后直接粘贴还是只复制,以及各平台要用户处理的事
+/// (Mac 的辅助功能权限、Linux Wayland 的系统快捷键)。见 design/quick-paste-and-favorites.md 第 9 节。
+class QuickPasteSection extends StatelessWidget {
+ const QuickPasteSection({super.key, required this.config, required this.onUpdate});
+
+ final Config config;
+ final Future<void> Function(Config next) onUpdate;
+
+ @override
+ Widget build(BuildContext context) {
+ final state = AppScope.of(context);
+ final l = context.l10n;
+ final p = context.palette;
+ final enabled = !config.quickPasteDisabled;
+ final qp = state.quickPaste;
+ final hotkey = Hotkey.parse(config.quickPasteHotkey) ?? Hotkey.fallback;
+ // 旧版后台服务没有快捷窗口,qp 为 null:不提示「没在运行」
+ final notRunning = enabled && qp != null && !qp.running && state.isOnline;
+ final portal = qp?.hotkeySource == 'portal';
+ final systemShortcut = qp?.hotkeySource == 'system_shortcut';
+
+ return GroupSection(
+ title: l.quickPaste,
+ child: GroupBox(
+ children: [
+ SettingRow(
+ title: l.quickPasteWindow,
+ description: notRunning ? l.quickPasteNotRunning : l.quickPasteWindowDesc,
+ child: SmallSwitch(
+ value: enabled,
+ onChanged: (v) => onUpdate(config.deepCopy()..quickPasteDisabled = !v),
+ ),
+ ),
+ if (enabled && portal)
+ SettingRow(
+ title: l.quickPasteShortcut,
+ description: l.quickPastePortalKey,
+ child: _KeyCap(text: qp!.hotkey.isEmpty ? '—' : (Hotkey.parse(qp.hotkey)?.display() ?? qp.hotkey)),
+ )
+ else if (enabled)
+ _ShortcutRow(
+ hotkey: hotkey,
+ error: _hotkeyError(l, qp, hotkey),
+ onChanged: (h) => onUpdate(config.deepCopy()..quickPasteHotkey = h.setting),
+ ),
+ if (enabled && systemShortcut) _SystemShortcutRow(hotkey: hotkey),
+ if (enabled)
+ SettingRow(
+ title: l.quickPasteAfterPick,
+ description: Platform.isLinux && (qp?.pasteUnavailableReason == 'wayland') ? l.quickPasteWaylandDesc : null,
+ child: Segmented<bool>(
+ value: !config.quickPasteCopyOnly,
+ segments: [(true, l.quickPastePasteIt), (false, l.quickPasteCopyIt)],
+ onChanged: (paste) => onUpdate(config.deepCopy()..quickPasteCopyOnly = !paste),
+ ),
+ ),
+ if (enabled && Platform.isMacOS && qp != null && qp.running && !config.quickPasteCopyOnly)
+ SettingRow(
+ title: l.quickPasteAccessibility,
+ description: l.quickPasteAccessibilityDesc,
+ child: qp.pasteUnavailableReason == 'not_trusted'
+ ? OutlinedButton(
+ onPressed: () async {
+ try {
+ await state.sendQuickPasteCommand('request_permission');
+ } catch (e) {
+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);
+ }
+ },
+ child: Text(l.quickPasteAllow),
+ )
+ : Text(l.quickPasteAllowed, style: context.text.bodyMedium?.copyWith(color: p.textDim)),
+ ),
+ ],
+ ),
+ );
+ }
+
+ static String? _hotkeyError(AppLocalizations l, QuickPasteStatus? qp, Hotkey hotkey) {
+ final err = qp?.hotkeyError ?? '';
+ if (err.isEmpty || qp?.running != true) return null;
+ // 快捷窗口报的是它实际在用的那个;设置刚改过、它还没重新注册时不显示旧的错误
+ if (qp!.hotkey.isNotEmpty && qp.hotkey != hotkey.canonical) return null;
+ if (err == 'in_use') return l.quickPasteInUse(hotkey.display());
+ return l.quickPasteHotkeyFailed(hotkey.display(), err);
+ }
+}
+
+/// 快捷键的样子:一个带边框的小方块。
+class _KeyCap extends StatelessWidget {
+ const _KeyCap({required this.text, this.active = false});
+
+ final String text;
+ final bool active;
+
+ @override
+ Widget build(BuildContext context) {
+ final p = context.palette;
+ return Container(
+ constraints: const BoxConstraints(minWidth: 64),
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
+ decoration: BoxDecoration(
+ color: p.surface,
+ borderRadius: BorderRadius.circular(Radii.sm),
+ border: Border.all(color: active ? p.accent : p.border, width: active ? 1.5 : 1),
+ ),
+ child: Text(text, textAlign: TextAlign.center, style: context.text.labelLarge),
+ );
+ }
+}
+
+/// 快捷键一行:点一下进入录制,按下新的组合就保存;Esc 或点别处取消。
+/// 录制期间请快捷窗口暂停全局快捷键,否则按下当前的快捷键会把快捷窗口叫出来。
+class _ShortcutRow extends StatefulWidget {
+ const _ShortcutRow({required this.hotkey, required this.error, required this.onChanged});
+
+ final Hotkey hotkey;
+ final String? error;
+ final Future<void> Function(Hotkey) onChanged;
+
+ @override
+ State<_ShortcutRow> createState() => _ShortcutRowState();
+}
+
+class _ShortcutRowState extends State<_ShortcutRow> {
+ final _focus = FocusNode();
+ bool _recording = false;
+ String? _hint;
+
+ @override
+ void initState() {
+ super.initState();
+ _focus.addListener(() {
+ if (!_focus.hasFocus && _recording) _stop();
+ });
+ }
+
+ @override
+ void dispose() {
+ if (_recording) _command('resume_hotkey');
+ _focus.dispose();
+ super.dispose();
+ }
+
+ void _command(String c) {
+ // 快捷窗口没在运行时发不出去,无所谓
+ AppScope.read(context).sendQuickPasteCommand(c).catchError((_) {});
+ }
+
+ void _start() {
+ setState(() {
+ _recording = true;
+ _hint = null;
+ });
+ _command('suspend_hotkey');
+ _focus.requestFocus();
+ }
+
+ void _stop() {
+ if (!_recording) return;
+ setState(() => _recording = false);
+ _command('resume_hotkey');
+ }
+
+ KeyEventResult _onKey(FocusNode _, KeyEvent e) {
+ if (!_recording || e is! KeyDownEvent) return KeyEventResult.ignored;
+ if (e.logicalKey == LogicalKeyboardKey.escape) {
+ _stop();
+ _focus.unfocus();
+ return KeyEventResult.handled;
+ }
+ final h = Hotkey.fromKey(e.logicalKey, e.physicalKey, Hotkey.pressedModifiers());
+ if (h == null) return KeyEventResult.handled; // 修饰键本身,等下一个键
+ if (!h.usable) {
+ final l = context.l10n;
+ setState(() => _hint = Platform.isMacOS ? l.quickPasteNeedsModifier : l.quickPasteNeedsModifierPc);
+ return KeyEventResult.handled;
+ }
+ _stop();
+ _focus.unfocus();
+ widget.onChanged(h);
+ return KeyEventResult.handled;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l = context.l10n;
+ final p = context.palette;
+ final message = _recording ? _hint : widget.error;
+ return SettingRow(
+ title: l.quickPasteShortcut,
+ description: message ?? (_recording ? l.quickPasteRecording : l.quickPasteRecord),
+ descriptionColor: message != null ? p.danger : null,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (!_recording && widget.hotkey != Hotkey.fallback) ...[
+ TextButton(onPressed: () => widget.onChanged(Hotkey.fallback), child: Text(l.quickPasteUseDefault)),
+ const SizedBox(width: Insets.xs),
+ ],
+ Focus(
+ focusNode: _focus,
+ onKeyEvent: _onKey,
+ child: MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: _recording ? null : _start,
+ child: _KeyCap(
+ text: _recording ? '…' : widget.hotkey.display(),
+ active: _recording || message != null,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+/// Linux Wayland 上没有全局快捷键门户时:GNOME 上一键写入系统的自定义快捷键,其他桌面给出命令让用户自己加。
+class _SystemShortcutRow extends StatelessWidget {
+ const _SystemShortcutRow({required this.hotkey});
+
+ final Hotkey hotkey;
+
+ @override
+ Widget build(BuildContext context) {
+ final l = context.l10n;
+ if (!GnomeShortcut.supported) {
+ return SettingRow(
+ title: l.quickPasteAddShortcut,
+ description: l.quickPasteShortcutManual(GnomeShortcut.command),
+ child: const SizedBox.shrink(),
+ );
+ }
+ return SettingRow(
+ title: l.quickPasteAddShortcut,
+ description: l.quickPasteWaylandDesc,
+ child: OutlinedButton(
+ onPressed: () async {
+ try {
+ await GnomeShortcut.install(hotkey);
+ if (context.mounted) showToast(context, l.quickPasteShortcutAdded(hotkey.display()));
+ } catch (e) {
+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);
+ }
+ },
+ child: Text(l.quickPasteAddShortcut),
+ ),
+ );
+ }
+}
diff --git a/ui/lib/pages/settings_page.dart b/ui/lib/pages/settings_page.dart
index 3852788..84e46c0 100644
--- a/ui/lib/pages/settings_page.dart
+++ b/ui/lib/pages/settings_page.dart
@@ -14,6 +14,7 @@ import '../widgets/feedback_dialog.dart';
import '../widgets/update_dialog.dart';
import '../icons.dart';
import '../platform.dart';
+import 'quick_paste_settings.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@@ -235,6 +236,7 @@ class _SettingsPageState extends State<SettingsPage> {
],
),
),
+ QuickPasteSection(config: cfg, onUpdate: (next) => _update(state, next)),
GroupSection(
title: l.sync,
child: GroupBox(
@@ -360,6 +362,15 @@ class _SettingsPageState extends State<SettingsPage> {
),
),
),
+ // 硬链接、写时复制保存的副本实际占用更少,所以写「最多」
+ SettingRow(
+ title: l.favoritesUsage,
+ description: l.favoritesUsageDesc,
+ child: Text(
+ l.upToSize(humanBytes(state.favoritesBytes)),
+ style: context.text.bodyMedium?.copyWith(color: p.textDim),
+ ),
+ ),
],
),
),
diff --git a/ui/lib/picker/picker_host.dart b/ui/lib/picker/picker_host.dart
new file mode 100644
index 0000000..2eaba9d
--- /dev/null
+++ b/ui/lib/picker/picker_host.dart
@@ -0,0 +1,108 @@
+import 'package:flutter/services.dart';
+
+/// 快捷粘贴窗口的原生外壳(Mac 的 Swift、Windows 的 C++、Linux 的 C)。
+/// 全局快捷键、窗口的显示与隐藏、记下并还原原来的窗口、模拟粘贴键都由它做,Dart 只管列表与按键。
+/// 通道名与方法名三个平台一致,见 design/quick-paste-and-favorites.md 第 6、7 节。
+///
+/// Dart → 原生:
+/// setHotkey {hotkey, enabled} → {ok, error, source, hotkey}
+/// setSuspended {suspended} 设置页录制快捷键期间暂停
+/// pasteStatus → {available, reason}
+/// requestPermission Mac:请求辅助功能权限
+/// show / hide hide 会把焦点还给原来的窗口
+/// commit {paste} → {pasted, reason} 隐藏窗口、还原焦点,paste 时再模拟粘贴键
+/// ready Dart 准备好了;之前按下的快捷键这时才显示窗口
+/// quit 关掉快捷粘贴时退出进程
+/// 原生 → Dart:
+/// onShow 窗口刚显示出来
+/// onHide 窗口被收起(点了窗口外面、切到别的程序)
+/// onHotkeyChanged {hotkey} Wayland 上用户在系统设置里改了快捷键
+class PickerHost {
+ PickerHost([MethodChannel? channel]) : _ch = channel ?? const MethodChannel('pasteferry/picker');
+
+ final MethodChannel _ch;
+
+ VoidCallback? onShow;
+ VoidCallback? onHide;
+ ValueChanged<String>? onHotkeyChanged;
+
+ void listen() {
+ _ch.setMethodCallHandler((call) async {
+ switch (call.method) {
+ case 'onShow':
+ onShow?.call();
+ case 'onHide':
+ onHide?.call();
+ case 'onHotkeyChanged':
+ onHotkeyChanged?.call('${(call.arguments as Map?)?['hotkey'] ?? ''}');
+ }
+ return null;
+ });
+ }
+
+ Future<HotkeyResult> setHotkey(String hotkey, {required bool enabled}) async {
+ final r = await _invoke('setHotkey', {'hotkey': hotkey, 'enabled': enabled});
+ return HotkeyResult(
+ ok: r?['ok'] == true,
+ error: '${r?['error'] ?? (r == null ? 'unsupported' : '')}',
+ source: '${r?['source'] ?? 'native'}',
+ hotkey: '${r?['hotkey'] ?? hotkey}',
+ );
+ }
+
+ Future<void> setSuspended(bool suspended) => _invoke('setSuspended', {'suspended': suspended});
+
+ Future<PasteStatus> pasteStatus() async {
+ final r = await _invoke('pasteStatus');
+ return PasteStatus(available: r?['available'] == true, reason: '${r?['reason'] ?? 'unsupported'}');
+ }
+
+ Future<void> requestPermission() => _invoke('requestPermission');
+ Future<void> show() => _invoke('show');
+ Future<void> hide() => _invoke('hide');
+ Future<void> ready() => _invoke('ready');
+ Future<void> quit() => _invoke('quit');
+
+ Future<CommitResult> commit({required bool paste}) async {
+ final r = await _invoke('commit', {'paste': paste});
+ return CommitResult(pasted: r?['pasted'] == true, reason: '${r?['reason'] ?? ''}');
+ }
+
+ /// 原生外壳没实现(界面测试、在开发机上直接 flutter run)时返回 null,不抛异常。
+ Future<Map<Object?, Object?>?> _invoke(String method, [Map<String, Object?>? args]) async {
+ try {
+ final r = await _ch.invokeMethod<Object?>(method, args);
+ return r is Map ? r : const {};
+ } on MissingPluginException {
+ return null;
+ }
+ }
+}
+
+class HotkeyResult {
+ const HotkeyResult({required this.ok, required this.error, required this.source, required this.hotkey});
+ final bool ok;
+
+ /// in_use、invalid、unsupported,或者平台给的原文
+ final String error;
+
+ /// native、portal、system_shortcut
+ final String source;
+ final String hotkey;
+}
+
+class PasteStatus {
+ const PasteStatus({required this.available, required this.reason});
+ final bool available;
+
+ /// not_trusted(Mac 没授予辅助功能)、wayland
+ final String reason;
+}
+
+class CommitResult {
+ const CommitResult({required this.pasted, required this.reason});
+ final bool pasted;
+
+ /// 没粘贴的原因:not_trusted、wayland、elevated(目标窗口以管理员身份运行)、failed
+ final String reason;
+}
diff --git a/ui/lib/picker/picker_main.dart b/ui/lib/picker/picker_main.dart
new file mode 100644
index 0000000..f47e5f1
--- /dev/null
+++ b/ui/lib/picker/picker_main.dart
@@ -0,0 +1,12 @@
+import 'package:flutter/widgets.dart';
+
+import 'picker_state.dart';
+import 'picker_view.dart';
+
+/// 快捷粘贴窗口进程的入口:界面程序带着 --picker 启动(Mac 上是 PasteFerryPicker.app 用同一份 Dart 代码启动)。
+void runPicker() {
+ WidgetsFlutterBinding.ensureInitialized();
+ final state = PickerState();
+ runApp(PickerApp(state: state));
+ state.start();
+}
diff --git a/ui/lib/picker/picker_state.dart b/ui/lib/picker/picker_state.dart
new file mode 100644
index 0000000..c8998f8
--- /dev/null
+++ b/ui/lib/picker/picker_state.dart
@@ -0,0 +1,576 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:grpc/grpc.dart';
+
+import '../app_state.dart' show AppState, matchesSearch;
+import '../background_service.dart' show appVersion;
+import '../daemon_client.dart';
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../gen/pasteferry/v1/daemon.pbgrpc.dart' show DaemonServiceClient;
+import '../hotkey.dart';
+import '../records.dart';
+import '../widgets/record_hover.dart';
+import 'picker_host.dart';
+
+/// 快捷窗口的页签:前五个按类型筛选复制记录,最后一个是收藏。
+enum PickerTab { all, text, link, image, file, favorites }
+
+extension PickerTabX on PickerTab {
+ RecordFilter? get filter => switch (this) {
+ PickerTab.all => RecordFilter.all,
+ PickerTab.text => RecordFilter.text,
+ PickerTab.link => RecordFilter.link,
+ PickerTab.image => RecordFilter.image,
+ PickerTab.file => RecordFilter.file,
+ PickerTab.favorites => null,
+ };
+}
+
+/// 快捷粘贴窗口的状态:连着后台服务,保留最近的复制记录与全部收藏,呼出时不用临时查询。
+/// 见 design/quick-paste-and-favorites.md 第 2、6 节。
+class PickerState extends ChangeNotifier implements RecordDetails {
+ PickerState({PickerHost? host}) : host = host ?? PickerHost();
+
+ final PickerHost host;
+
+ DaemonConnection? _conn;
+ StreamSubscription<Event>? _events;
+ StreamController<QuickPasteStatus>? _statusOut;
+ StreamSubscription<QuickPasteCommand>? _commands;
+ Timer? _retry;
+
+ Config? _config;
+ final List<ClipRecord> _records = [];
+ final List<ClipRecord> _favorites = [];
+ final Map<String, ClipDetail> _details = {};
+ final Map<String, String> _thumbs = {};
+ final Map<String, double> _progress = {};
+
+ /// 界面语言跟着设置走,单独通知,免得每次列表变化都重建 MaterialApp
+ final language = ValueNotifier<String>('');
+
+ bool _connected = false;
+ bool get connected => _connected;
+ Config? get config => _config;
+
+ // ── 原生外壳报上来的 ──
+ HotkeyResult? _hotkey;
+ String _registered = '';
+ PasteStatus _paste = const PasteStatus(available: false, reason: 'unsupported');
+ QuickPasteStatus? _lastSent;
+
+ // ── 界面 ──
+ PickerTab _tab = PickerTab.all;
+ String _query = '';
+ int _selected = 0;
+ List<ClipRecord>? _results;
+ Timer? _searchTimer;
+ int _searchSeq = 0;
+ String? _error;
+
+ /// 选中了一条还没下载的大文件:下完再粘贴
+ String? _pendingId;
+ bool _pendingPlain = false, _pendingCopyOnly = false;
+
+ /// 每次呼出时加一,界面据此把焦点放回搜索框、清空输入
+ final shown = ValueNotifier<int>(0);
+
+ PickerTab get tab => _tab;
+ String get query => _query;
+ int get selected => _selected;
+ String? get error => _error;
+ String? get pendingId => _pendingId;
+ double? progressOf(String id) => _progress[id];
+ String? thumbnailOf(String id) => _thumbs[id];
+
+ bool get copyOnly => _config?.quickPasteCopyOnly ?? false;
+
+ /// 选中后能不能自动粘贴;不能的原因见 [pasteBlockedReason]
+ bool get canPaste => !copyOnly && _paste.available;
+
+ /// copy_only、not_trusted、wayland,能粘贴时为空
+ String get pasteBlockedReason => copyOnly ? 'copy_only' : (_paste.available ? '' : _paste.reason);
+
+ /// 当前页签、搜索词下的列表。
+ List<ClipRecord> get visible {
+ final f = _tab.filter;
+ final base = f == null ? _favorites : _records.where(f.matches).toList();
+ if (_query.trim().isEmpty) return base;
+ // 后台服务的结果回来之前,先在已加载的里面找,打字时列表立刻有反应
+ return _results ?? base.where((r) => matchesSearch(r, _query.trim())).toList();
+ }
+
+ // ─────────────────────────── 启动与连接 ───────────────────────────
+
+ Future<void> start() async {
+ host
+ ..onShow = _onShow
+ ..onHide = _onHide
+ ..onHotkeyChanged = (h) {
+ _hotkey = HotkeyResult(ok: true, error: '', source: _hotkey?.source ?? 'portal', hotkey: h);
+ _sendStatus();
+ }
+ ..listen();
+ await connect();
+ await host.ready();
+ }
+
+ Future<void> connect() async {
+ _retry?.cancel();
+ try {
+ final conn = await DaemonConnection.connect();
+ final results = await Future.wait([
+ conn.client.listHistory(ListHistoryRequest(limit: 200)),
+ conn.client.listHistory(ListHistoryRequest(limit: 500, favorites: true)),
+ conn.client.getConfig(Empty()),
+ ]);
+ _conn = conn;
+ _records
+ ..clear()
+ ..addAll((results[0] as ListHistoryResponse).records);
+ _favorites
+ ..clear()
+ ..addAll((results[1] as ListHistoryResponse).records.where((r) => r.favorite));
+ _config = results[2] as Config;
+ language.value = _config!.language;
+ _events = conn.client.subscribe(SubscribeRequest()).listen(
+ _onEvent,
+ onError: (_) => _lost(),
+ onDone: _lost,
+ );
+ _startSession(conn);
+ _connected = true;
+ notifyListeners();
+ await _applyConfig();
+ } catch (_) {
+ _lost();
+ }
+ }
+
+ void _lost() {
+ _events?.cancel();
+ _events = null;
+ _commands?.cancel();
+ _commands = null;
+ _statusOut?.close();
+ _statusOut = null;
+ _lastSent = null;
+ _conn?.close();
+ _conn = null;
+ if (_connected) {
+ _connected = false;
+ notifyListeners();
+ }
+ // 后台服务可能正在重启(更新、换设置),过一会儿再连
+ _retry?.cancel();
+ _retry = Timer(const Duration(seconds: 2), connect);
+ }
+
+ void _startSession(DaemonConnection conn) {
+ final out = StreamController<QuickPasteStatus>();
+ _statusOut = out;
+ _commands = conn.client.quickPasteSession(out.stream).listen(_onCommand, onError: (_) {}, onDone: () {});
+ }
+
+ /// 按设置注册快捷键;关掉了快捷粘贴就退出进程(Windows、Linux 上后台服务不会再拉起它,
+ /// Mac 上 LaunchAgent 只在异常退出时重启)。
+ Future<void> _applyConfig() async {
+ final c = _config;
+ if (c == null) return;
+ if (c.quickPasteDisabled) {
+ await host.setHotkey('', enabled: false);
+ await host.quit();
+ return;
+ }
+ final hk = (Hotkey.parse(c.quickPasteHotkey) ?? Hotkey.fallback).canonical;
+ if (hk != _registered) {
+ _hotkey = await host.setHotkey(hk, enabled: true);
+ _registered = hk;
+ }
+ _paste = await host.pasteStatus();
+ _sendStatus();
+ notifyListeners();
+ }
+
+ QuickPasteStatus get _status => QuickPasteStatus(
+ running: true,
+ hotkey: _hotkey?.hotkey ?? '',
+ hotkeyError: _hotkey == null || _hotkey!.ok ? '' : _hotkey!.error,
+ hotkeySource: _hotkey?.source ?? 'native',
+ pasteAvailable: canPaste,
+ pasteUnavailableReason: pasteBlockedReason,
+ version: appVersion,
+ );
+
+ void _sendStatus() {
+ final out = _statusOut;
+ if (out == null || out.isClosed) return;
+ final st = _status;
+ if (st == _lastSent) return;
+ _lastSent = st;
+ out.add(st);
+ }
+
+ Timer? _permissionPoll;
+
+ Future<void> _onCommand(QuickPasteCommand c) async {
+ switch (c.command) {
+ case 'request_permission':
+ await host.requestPermission();
+ // 用户去系统设置里打开开关要一会儿:一分钟内每秒看一次
+ _permissionPoll?.cancel();
+ var ticks = 0;
+ _permissionPoll = Timer.periodic(const Duration(seconds: 1), (t) async {
+ _paste = await host.pasteStatus();
+ _sendStatus();
+ if (_paste.available || ++ticks >= 60) t.cancel();
+ });
+ case 'suspend_hotkey':
+ await host.setSuspended(true);
+ case 'resume_hotkey':
+ await host.setSuspended(false);
+ case 'show':
+ await host.show();
+ }
+ }
+
+ void _onEvent(Event ev) {
+ switch (ev.whichPayload()) {
+ case Event_Payload.clipAdded:
+ _upsert(ev.clipAdded);
+ case Event_Payload.clipUpdated:
+ _upsert(ev.clipUpdated);
+ case Event_Payload.clipRemoved:
+ _records.removeWhere((r) => r.id == ev.clipRemoved);
+ _favorites.removeWhere((r) => r.id == ev.clipRemoved);
+ _results?.removeWhere((r) => r.id == ev.clipRemoved);
+ _details.remove(ev.clipRemoved);
+ _thumbs.remove(ev.clipRemoved);
+ case Event_Payload.configChanged:
+ _config = ev.configChanged;
+ language.value = _config!.language;
+ _applyConfig();
+ case Event_Payload.progress:
+ final p = ev.progress;
+ if (p.total > 0) _progress[p.clipId] = (p.transferred.toInt() / p.total.toInt()).clamp(0.0, 1.0);
+ default:
+ return;
+ }
+ _clampSelection();
+ notifyListeners();
+ }
+
+ /// 与主窗口的 AppState 同样的规则:按 favorite 分到复制记录或收藏,取消收藏的同一条换过去。
+ void _upsert(ClipRecord r) {
+ if (r.favorite) {
+ _records.removeWhere((x) => x.id == r.id);
+ final i = _favorites.indexWhere((x) => x.id == r.id);
+ if (i >= 0) {
+ _favorites[i] = r;
+ } else {
+ _favorites.add(r);
+ }
+ _favorites.sort((a, b) => b.favoritedAtUnix.compareTo(a.favoritedAtUnix));
+ } else {
+ _favorites.removeWhere((x) => x.id == r.id);
+ final i = _records.indexWhere((x) => x.id == r.id);
+ if (i >= 0) {
+ _records[i] = r;
+ } else {
+ final at = _records.indexWhere((x) => x.createdAtUnix < r.createdAtUnix);
+ _records.insert(at < 0 ? _records.length : at, r);
+ if (_records.length > 500) _records.removeLast();
+ }
+ }
+ final ri = _results?.indexWhere((x) => x.id == r.id) ?? -1;
+ if (ri >= 0) _results![ri] = r.deepCopy()..textPreview = _results![ri].textPreview;
+ if (r.status != ClipStatus.CLIP_STATUS_FETCHING) _progress.remove(r.id);
+ // 等着下载完再粘贴的那一条就绪了
+ if (r.id == _pendingId && r.status == ClipStatus.CLIP_STATUS_READY) {
+ _pendingId = null;
+ choose(r, plain: _pendingPlain, copyOnly: _pendingCopyOnly);
+ } else if (r.id == _pendingId && r.status == ClipStatus.CLIP_STATUS_FAILED) {
+ _pendingId = null;
+ _error = r.error;
+ }
+ }
+
+ // ─────────────────────────── 呼出与收起 ───────────────────────────
+
+ void _onShow() {
+ _reset();
+ shown.value++;
+ // 辅助功能权限可能刚在系统设置里打开
+ host.pasteStatus().then((p) {
+ _paste = p;
+ _sendStatus();
+ notifyListeners();
+ });
+ notifyListeners();
+ }
+
+ void _onHide() {
+ _reset();
+ notifyListeners();
+ }
+
+ /// 每次呼出都从「全部」、第一条、空搜索开始。
+ void _reset() {
+ _tab = PickerTab.all;
+ _query = '';
+ _selected = 0;
+ _results = null;
+ _searchTimer?.cancel();
+ _searchSeq++;
+ _error = null;
+ _pendingId = null;
+ }
+
+ Future<void> close() async {
+ _reset();
+ notifyListeners();
+ await host.hide();
+ }
+
+ // ─────────────────────────── 列表与搜索 ───────────────────────────
+
+ void setTab(PickerTab t) {
+ if (t == _tab) return;
+ _tab = t;
+ _selected = 0;
+ _results = null;
+ _scheduleSearch(Duration.zero);
+ notifyListeners();
+ }
+
+ void cycleTab(int delta) {
+ const tabs = PickerTab.values;
+ setTab(tabs[(tabs.indexOf(_tab) + delta) % tabs.length]);
+ }
+
+ void setQuery(String q) {
+ _query = q;
+ _selected = 0;
+ _results = null;
+ _error = null;
+ _scheduleSearch(const Duration(milliseconds: 150));
+ notifyListeners();
+ }
+
+ void select(int i) {
+ if (i == _selected || i < 0 || i >= visible.length) return;
+ _selected = i;
+ notifyListeners();
+ }
+
+ void moveSelection(int delta) {
+ final n = visible.length;
+ if (n == 0) return;
+ _selected = (_selected + delta).clamp(0, n - 1);
+ notifyListeners();
+ }
+
+ void _clampSelection() {
+ final n = visible.length;
+ if (_selected >= n) _selected = n == 0 ? 0 : n - 1;
+ }
+
+ void _scheduleSearch(Duration delay) {
+ _searchTimer?.cancel();
+ if (_query.trim().isEmpty) return;
+ _searchTimer = Timer(delay, _runSearch);
+ }
+
+ Future<void> _runSearch() async {
+ final q = _query.trim();
+ final tab = _tab;
+ final seq = ++_searchSeq;
+ try {
+ final r = await requestSearch(q, tab);
+ if (seq != _searchSeq || q != _query.trim() || tab != _tab) return;
+ if (r.searched) {
+ _results = r.records.toList();
+ _clampSelection();
+ notifyListeners();
+ }
+ } catch (_) {
+ // 搜不了就用已加载的记录里找到的
+ }
+ }
+
+ @protected
+ Future<ListHistoryResponse> requestSearch(String query, PickerTab tab) {
+ final req = ListHistoryRequest(limit: 100, query: query, favorites: tab == PickerTab.favorites);
+ switch (tab) {
+ case PickerTab.text:
+ req.kindFilter = ClipKind.CLIP_KIND_TEXT;
+ case PickerTab.link:
+ req.linksOnly = true;
+ case PickerTab.image:
+ req.kindFilter = ClipKind.CLIP_KIND_IMAGE;
+ case PickerTab.file:
+ req.kindFilter = ClipKind.CLIP_KIND_FILE;
+ case PickerTab.all || PickerTab.favorites:
+ }
+ return _client.listHistory(req);
+ }
+
+ // ─────────────────────────── 选中、收藏、删除 ───────────────────────────
+
+ /// 能选的:已就绪的,或者还没下载的大文件(先下载再粘贴)。过期、失败、收藏还在保存的不能选。
+ static bool selectable(ClipRecord r) => switch (r.status) {
+ ClipStatus.CLIP_STATUS_READY => true,
+ ClipStatus.CLIP_STATUS_REMOTE_ONLY || ClipStatus.CLIP_STATUS_FETCHING => !r.favorite && !r.outgoing,
+ _ => false,
+ };
+
+ /// 选中一条:放进剪贴板,收起窗口,把焦点还给原来的窗口,能粘贴时模拟粘贴键。
+ /// [plain] 只写纯文本;[copyOnly] 只放进剪贴板,不粘贴。
+ Future<void> choose(ClipRecord r, {bool plain = false, bool copyOnly = false}) async {
+ if (!selectable(r)) return;
+ _error = null;
+ if (r.status != ClipStatus.CLIP_STATUS_READY) {
+ _pendingId = r.id;
+ _pendingPlain = plain;
+ _pendingCopyOnly = copyOnly;
+ notifyListeners();
+ if (r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY) {
+ try {
+ await requestFetch(r.id);
+ } catch (e) {
+ _pendingId = null;
+ _error = AppState.describeError(e);
+ notifyListeners();
+ }
+ }
+ return;
+ }
+ try {
+ await requestApply(r.id, plain);
+ } catch (e) {
+ _error = AppState.describeError(e);
+ notifyListeners();
+ return;
+ }
+ final paste = !copyOnly && !this.copyOnly;
+ _reset();
+ notifyListeners();
+ await host.commit(paste: paste);
+ }
+
+ Future<void> chooseIndex(int i, {bool plain = false, bool copyOnly = false}) async {
+ final list = visible;
+ if (i < 0 || i >= list.length) return;
+ _selected = i;
+ await choose(list[i], plain: plain, copyOnly: copyOnly);
+ }
+
+ Future<void> toggleFavorite(ClipRecord r) async {
+ try {
+ await requestFavorite(r.id, !(r.favorite || r.favorited));
+ } catch (e) {
+ _error = AppState.describeError(e);
+ notifyListeners();
+ }
+ }
+
+ Future<void> delete(ClipRecord r) async {
+ if (r.favorite) return; // 收藏里没有删除
+ try {
+ await _client.deleteHistory(DeleteHistoryRequest(ids: [r.id]));
+ _records.removeWhere((x) => x.id == r.id);
+ _results?.removeWhere((x) => x.id == r.id);
+ _clampSelection();
+ notifyListeners();
+ } catch (e) {
+ _error = AppState.describeError(e);
+ notifyListeners();
+ }
+ }
+
+ @protected
+ Future<void> requestApply(String id, bool plain) => _client.applyToClipboard(
+ ApplyToClipboardRequest(clipId: id, plainText: plain),
+ options: CallOptions(timeout: const Duration(seconds: 5)),
+ );
+
+ /// 下载但不覆盖剪贴板:下完由 [choose] 放进剪贴板再粘贴
+ @protected
+ Future<void> requestFetch(String id) => _client.fetch(FetchRequest(clipId: id, preserveClipboard: true));
+
+ @protected
+ Future<void> requestFavorite(String id, bool favorite) =>
+ _client.setFavorite(SetFavoriteRequest(clipId: id, favorite: favorite));
+
+ /// 图片行的小缩略图:取一次本机路径,记下来。
+ Future<void> loadThumbnail(ClipRecord r) async {
+ if (_thumbs.containsKey(r.id) || r.status != ClipStatus.CLIP_STATUS_READY) return;
+ _thumbs[r.id] = '';
+ try {
+ final p = await imagePreview(r.id);
+ if (p.path.isNotEmpty && File(p.path).existsSync()) {
+ _thumbs[r.id] = p.path;
+ notifyListeners();
+ }
+ } catch (_) {}
+ }
+
+ // ─────────────────────────── 悬停提示框 ───────────────────────────
+
+ @override
+ Future<ClipDetail> clipDetail(String clipId) async =>
+ _details[clipId] ??= await _client.getClipDetail(GetClipDetailRequest(clipId: clipId));
+
+ @override
+ Future<GetImagePreviewResponse> imagePreview(String clipId, {int index = 0}) => _client.getImagePreview(
+ GetImagePreviewRequest(clipId: clipId, index: index),
+ options: CallOptions(timeout: const Duration(seconds: 20)),
+ );
+
+ DaemonServiceClient get _client {
+ final c = _conn;
+ if (c == null) throw DaemonNotRunning('快捷窗口还没连上后台服务');
+ return c.client;
+ }
+
+ /// 测试用:直接填入数据,不连接后台服务。
+ @visibleForTesting
+ void debugSeed({
+ required Config config,
+ List<ClipRecord> records = const [],
+ List<ClipRecord> favorites = const [],
+ PasteStatus paste = const PasteStatus(available: true, reason: ''),
+ }) {
+ _config = config;
+ language.value = config.language;
+ _records
+ ..clear()
+ ..addAll(records);
+ _favorites
+ ..clear()
+ ..addAll(favorites);
+ _paste = paste;
+ _connected = true;
+ notifyListeners();
+ }
+
+ @visibleForTesting
+ void debugEvent(Event ev) => _onEvent(ev);
+
+ @visibleForTesting
+ void debugShow() => _onShow();
+
+ @override
+ void dispose() {
+ _retry?.cancel();
+ _searchTimer?.cancel();
+ _permissionPoll?.cancel();
+ _events?.cancel();
+ _commands?.cancel();
+ _statusOut?.close();
+ _conn?.close();
+ super.dispose();
+ }
+}
diff --git a/ui/lib/picker/picker_view.dart b/ui/lib/picker/picker_view.dart
new file mode 100644
index 0000000..b4bd332
--- /dev/null
+++ b/ui/lib/picker/picker_view.dart
@@ -0,0 +1,576 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../i18n.dart';
+import '../icons.dart';
+import '../records.dart';
+import '../theme.dart';
+import '../widgets/common.dart' show humanBytes, relativeTime;
+import '../widgets/record_hover.dart';
+import 'picker_state.dart';
+
+/// 快捷粘贴窗口。窗口本身由原生外壳创建(Mac 上是不抢焦点的 NSPanel),大小固定,这里画满整个窗口。
+/// 见 design/quick-paste-and-favorites.md 第 2.6 节的示意图。
+class PickerApp extends StatelessWidget {
+ const PickerApp({super.key, required this.state});
+
+ final PickerState state;
+
+ @override
+ Widget build(BuildContext context) {
+ return ValueListenableBuilder<String>(
+ valueListenable: state.language,
+ builder: (context, language, _) {
+ final locale = localeFromSetting(language);
+ final tag = (locale ?? resolveLocale(WidgetsBinding.instance.platformDispatcher.locales)).toLanguageTag();
+ ThemeData theme(Brightness b) => buildTheme(b, language: tag).copyWith(
+ // 窗口是透明的,圆角外面要透出桌面(Mac)
+ scaffoldBackgroundColor: Colors.transparent,
+ canvasColor: Colors.transparent,
+ );
+ return MaterialApp(
+ title: 'PasteFerry',
+ debugShowCheckedModeBanner: false,
+ color: Colors.transparent,
+ theme: theme(Brightness.light),
+ darkTheme: theme(Brightness.dark),
+ locale: locale,
+ supportedLocales: supportedLocales,
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ localeListResolutionCallback: (preferred, _) => resolveLocale(preferred),
+ builder: (context, child) {
+ appL10n = context.l10n;
+ return child!;
+ },
+ home: PickerView(state: state),
+ );
+ },
+ );
+ }
+}
+
+class PickerView extends StatefulWidget {
+ const PickerView({super.key, required this.state});
+
+ final PickerState state;
+
+ /// 每一行的高度
+ static const rowHeight = 36.0;
+
+ @override
+ State<PickerView> createState() => _PickerViewState();
+}
+
+class _PickerViewState extends State<PickerView> {
+ final _search = TextEditingController();
+ final _focus = FocusNode();
+ final _scroll = ScrollController();
+
+ PickerState get s => widget.state;
+ static final bool _mac = Platform.isMacOS;
+
+ @override
+ void initState() {
+ super.initState();
+ s.shown.addListener(_onShown);
+ s.addListener(_followSelection);
+ }
+
+ @override
+ void dispose() {
+ s.shown.removeListener(_onShown);
+ s.removeListener(_followSelection);
+ _search.dispose();
+ _focus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ void _onShown() {
+ _search.clear();
+ if (_scroll.hasClients) _scroll.jumpTo(0);
+ _focus.requestFocus();
+ }
+
+ /// 用键盘上下移动时,选中的那一行要留在视野里。
+ void _followSelection() {
+ if (!_scroll.hasClients) return;
+ final top = s.selected * PickerView.rowHeight;
+ final view = _scroll.position.viewportDimension;
+ if (top < _scroll.offset) {
+ _scroll.jumpTo(top);
+ } else if (top + PickerView.rowHeight > _scroll.offset + view) {
+ _scroll.jumpTo(top + PickerView.rowHeight - view);
+ }
+ }
+
+ bool get _composing => _search.value.composing.isValid;
+
+ /// 修饰键:Mac 上是 ⌘,其他平台是 Ctrl(序号用 Alt)
+ bool get _cmd => _mac ? HardwareKeyboard.instance.isMetaPressed : HardwareKeyboard.instance.isControlPressed;
+
+ KeyEventResult _onKey(FocusNode _, KeyEvent e) {
+ if (e is! KeyDownEvent && e is! KeyRepeatEvent) return KeyEventResult.ignored;
+ // 正在用输入法打字:数字选候选、回车上屏,都交给输入法
+ if (_composing) return KeyEventResult.ignored;
+ final kb = HardwareKeyboard.instance;
+ final k = e.logicalKey;
+ final list = s.visible;
+ final current = s.selected < list.length ? list[s.selected] : null;
+
+ if (k == LogicalKeyboardKey.escape) {
+ if (_search.text.isNotEmpty) {
+ _search.clear();
+ s.setQuery('');
+ } else {
+ s.close();
+ }
+ return KeyEventResult.handled;
+ }
+ if (k == LogicalKeyboardKey.arrowDown || (_mac && kb.isControlPressed && k == LogicalKeyboardKey.keyN)) {
+ s.moveSelection(1);
+ return KeyEventResult.handled;
+ }
+ if (k == LogicalKeyboardKey.arrowUp || (_mac && kb.isControlPressed && k == LogicalKeyboardKey.keyP)) {
+ s.moveSelection(-1);
+ return KeyEventResult.handled;
+ }
+ if (k == LogicalKeyboardKey.tab) {
+ s.cycleTab(kb.isShiftPressed ? -1 : 1);
+ return KeyEventResult.handled;
+ }
+ if (k == LogicalKeyboardKey.enter || k == LogicalKeyboardKey.numpadEnter) {
+ if (e is KeyRepeatEvent || current == null) return KeyEventResult.handled;
+ s.choose(current, plain: kb.isShiftPressed, copyOnly: _cmd);
+ return KeyEventResult.handled;
+ }
+ if (_cmd && k == LogicalKeyboardKey.keyD && current != null) {
+ s.toggleFavorite(current);
+ return KeyEventResult.handled;
+ }
+ final delete = (_mac && kb.isMetaPressed && k == LogicalKeyboardKey.backspace) ||
+ (!_mac && kb.isShiftPressed && k == LogicalKeyboardKey.delete);
+ if (delete && current != null && s.tab != PickerTab.favorites) {
+ s.delete(current);
+ return KeyEventResult.handled;
+ }
+ // 序号:搜索框为空时直接按数字;任何时候按住 ⌘(Mac)或 Alt(Windows、Linux)
+ final digit = _digit(e);
+ if (digit != null && e is KeyDownEvent) {
+ final withModifier = _mac ? kb.isMetaPressed : kb.isAltPressed;
+ if (withModifier || (_search.text.isEmpty && !kb.isControlPressed && !kb.isMetaPressed && !kb.isAltPressed)) {
+ s.chooseIndex(digit - 1);
+ return KeyEventResult.handled;
+ }
+ }
+ return KeyEventResult.ignored;
+ }
+
+ static int? _digit(KeyEvent e) {
+ final u = e.physicalKey.usbHidUsage;
+ final one = PhysicalKeyboardKey.digit1.usbHidUsage;
+ if (u >= one && u <= PhysicalKeyboardKey.digit9.usbHidUsage) return 1 + u - one;
+ final pad = PhysicalKeyboardKey.numpad1.usbHidUsage;
+ if (u >= pad && u <= PhysicalKeyboardKey.numpad9.usbHidUsage) return 1 + u - pad;
+ return null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final p = context.palette;
+ return Material(
+ type: MaterialType.transparency,
+ child: Focus(
+ onKeyEvent: _onKey,
+ child: Container(
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: p.surface,
+ // Mac 上窗口透明,自己画圆角;Windows 11 的圆角由系统画,Linux 用直角
+ borderRadius: _mac ? BorderRadius.circular(Radii.lg) : null,
+ border: Border.all(color: p.border),
+ ),
+ child: ListenableBuilder(
+ listenable: s,
+ builder: (context, _) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _searchBar(context),
+ _tabs(context),
+ Divider(height: 1, color: p.separator),
+ Expanded(child: _list(context)),
+ Divider(height: 1, color: p.separator),
+ _footer(context),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _searchBar(BuildContext context) {
+ final p = context.palette;
+ final l = context.l10n;
+ return SizedBox(
+ height: 44,
+ child: Row(
+ children: [
+ const SizedBox(width: Insets.md),
+ Icon(AppIcons.search, size: 16, color: p.textFaint),
+ const SizedBox(width: Insets.sm),
+ Expanded(
+ child: TextField(
+ controller: _search,
+ focusNode: _focus,
+ autofocus: true,
+ onChanged: s.setQuery,
+ style: context.text.titleMedium?.copyWith(fontWeight: FontWeight.w400),
+ decoration: InputDecoration(
+ hintText: l.pickerSearch,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ contentPadding: EdgeInsets.zero,
+ ),
+ ),
+ ),
+ const SizedBox(width: Insets.md),
+ ],
+ ),
+ );
+ }
+
+ Widget _tabs(BuildContext context) {
+ final l = context.l10n;
+ final p = context.palette;
+ String label(PickerTab t) => t.filter?.label(l) ?? l.navFavorites;
+ return SizedBox(
+ height: 30,
+ child: Row(
+ children: [
+ const SizedBox(width: Insets.sm),
+ for (final t in PickerTab.values)
+ MouseRegion(
+ cursor: SystemMouseCursors.click,
+ child: GestureDetector(
+ onTap: () {
+ s.setTab(t);
+ _focus.requestFocus();
+ },
+ child: Container(
+ margin: const EdgeInsets.symmetric(horizontal: 2, vertical: 4),
+ padding: const EdgeInsets.symmetric(horizontal: Insets.sm),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: t == s.tab ? p.fill : Colors.transparent,
+ borderRadius: BorderRadius.circular(Radii.sm),
+ ),
+ child: Text(
+ label(t),
+ style: context.text.labelMedium?.copyWith(
+ color: t == s.tab ? p.text : p.textDim,
+ fontWeight: t == s.tab ? FontWeight.w600 : FontWeight.w400,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _list(BuildContext context) {
+ final l = context.l10n;
+ final p = context.palette;
+ if (!s.connected) return _empty(context, l.linkServiceNotRunning);
+ final list = s.visible;
+ if (list.isEmpty) {
+ final q = s.query.trim();
+ return _empty(
+ context,
+ q.isNotEmpty
+ ? l.searchEmptyTitle(q)
+ : s.tab == PickerTab.favorites
+ ? l.favoritesEmptyTitle
+ : s.tab == PickerTab.all
+ ? l.historyEmptyTitle
+ : l.historyEmptyFilteredTitle,
+ );
+ }
+ return ListView.builder(
+ controller: _scroll,
+ padding: const EdgeInsets.symmetric(vertical: Insets.xs),
+ itemExtent: PickerView.rowHeight,
+ itemCount: list.length,
+ itemBuilder: (context, i) => _PickerRow(
+ key: ValueKey(list[i].id),
+ state: s,
+ record: list[i],
+ index: i,
+ selected: i == s.selected,
+ number: i < 9 ? (s.query.trim().isEmpty ? '${i + 1}' : (_mac ? '⌘${i + 1}' : 'Alt+${i + 1}')) : null,
+ favoritesTab: s.tab == PickerTab.favorites,
+ dim: p.textFaint,
+ ),
+ );
+ }
+
+ Widget _empty(BuildContext context, String text) => Center(
+ child: Padding(
+ padding: const EdgeInsets.all(Insets.xl),
+ child: Text(text, style: context.text.bodyMedium?.copyWith(color: context.palette.textDim), textAlign: TextAlign.center),
+ ),
+ );
+
+ Widget _footer(BuildContext context) {
+ final l = context.l10n;
+ final p = context.palette;
+ final style = context.text.bodySmall?.copyWith(color: p.textDim);
+ final Widget content;
+ final pasteKey = _mac ? '⌘V' : 'Ctrl+V';
+ if (s.error != null) {
+ content = Text(s.error!, style: style?.copyWith(color: p.danger), maxLines: 1, overflow: TextOverflow.ellipsis);
+ } else if (s.pendingId != null) {
+ content = Text(l.pickerDownloading, style: style);
+ } else if (!s.canPaste) {
+ final notTrusted = s.pasteBlockedReason == 'not_trusted';
+ content = Row(
+ children: [
+ Flexible(
+ child: Text(
+ [l.pickerPasteManually(pasteKey), if (notTrusted) l.pickerGrantHint].join(' · '),
+ style: style,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (notTrusted) ...[
+ const SizedBox(width: Insets.sm),
+ TextButton(
+ onPressed: s.host.requestPermission,
+ style: TextButton.styleFrom(
+ visualDensity: VisualDensity.compact,
+ padding: const EdgeInsets.symmetric(horizontal: Insets.sm),
+ minimumSize: const Size(0, 22),
+ ),
+ child: Text(l.quickPasteAllow),
+ ),
+ ],
+ ],
+ );
+ } else {
+ // 按键画成小键帽,与系统菜单里快捷键的写法一致:Mac 用 ⇧ ⌘ 符号,其他平台写键名
+ const enter = _Key.enter();
+ final shift = _Key(_mac ? '⇧' : 'Shift');
+ final cmd = _Key(_mac ? '⌘' : 'Ctrl');
+ final fav = s.tab == PickerTab.favorites ? l.pickerUnfavoriteHint : l.favoriteAction;
+ content = SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ physics: const NeverScrollableScrollPhysics(),
+ child: Row(
+ children: [
+ _KeyHint(keys: const [enter], label: l.pickerPaste),
+ if (s.tab != PickerTab.favorites) _KeyHint(keys: [shift, enter], label: l.pickerPlainText),
+ _KeyHint(keys: [cmd, enter], label: l.pickerCopyOnly),
+ _KeyHint(keys: [cmd, const _Key('D')], label: fav),
+ _KeyHint(keys: [_Key(_mac ? 'esc' : 'Esc')], label: l.close),
+ ],
+ ),
+ );
+ }
+ return SizedBox(
+ height: 30,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: Insets.md),
+ child: Align(alignment: Alignment.centerLeft, child: content),
+ ),
+ );
+ }
+}
+
+/// 一个按键:文字,或者回车键的图标。
+class _Key {
+ const _Key(this.text) : enter = false;
+ const _Key.enter()
+ : text = '',
+ enter = true;
+ final String text;
+ final bool enter;
+}
+
+/// 底栏的一条按键提示:几个小键帽,后面跟着说明。
+class _KeyHint extends StatelessWidget {
+ const _KeyHint({required this.keys, required this.label});
+
+ final List<_Key> keys;
+ final String label;
+
+ @override
+ Widget build(BuildContext context) {
+ final p = context.palette;
+ final capStyle = context.text.labelSmall?.copyWith(color: p.textDim, fontSize: 10.5, height: 1.0);
+ return Padding(
+ padding: const EdgeInsets.only(right: Insets.md),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (final k in keys)
+ Container(
+ height: 16,
+ constraints: const BoxConstraints(minWidth: 16),
+ margin: const EdgeInsets.only(right: 2),
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: p.fill,
+ borderRadius: BorderRadius.circular(4),
+ border: Border.all(color: p.border, width: 0.5),
+ ),
+ child: k.enter ? Icon(AppIcons.returnKey, size: 10, color: p.textDim) : Text(k.text, style: capStyle),
+ ),
+ const SizedBox(width: 3),
+ Text(label, style: context.text.bodySmall?.copyWith(color: p.textDim)),
+ ],
+ ),
+ );
+ }
+}
+
+class _PickerRow extends StatelessWidget {
+ const _PickerRow({
+ super.key,
+ required this.state,
+ required this.record,
+ required this.index,
+ required this.selected,
+ required this.number,
+ required this.favoritesTab,
+ required this.dim,
+ });
+
+ final PickerState state;
+ final ClipRecord record;
+ final int index;
+ final bool selected;
+ final String? number;
+ final bool favoritesTab;
+ final Color dim;
+
+ @override
+ Widget build(BuildContext context) {
+ final p = context.palette;
+ final r = record;
+ final enabled = PickerState.selectable(r);
+ final onAccent = selected && enabled;
+ final fg = !enabled ? p.textFaint : (onAccent ? Colors.white : p.text);
+ final sub = onAccent ? Colors.white.withValues(alpha: 0.8) : p.textFaint;
+ final pending = state.pendingId == r.id;
+ final isImage = r.kind == ClipKind.CLIP_KIND_IMAGE || (r.kind == ClipKind.CLIP_KIND_FILE && r.imageCount == 1 && r.items.length == 1);
+ if (isImage) state.loadThumbnail(r);
+ final thumb = isImage ? state.thumbnailOf(r.id) : null;
+ final meta = [
+ if (r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY) humanBytes(r.totalSize.toInt()),
+ if (!r.outgoing) r.originDeviceName,
+ if (r.favorite) appL10n.favoritedAt(shortDate(favoritedTime(r))) else relativeTime(recordTime(r)),
+ ].join(' · ');
+
+ return RecordHover(
+ record: r,
+ details: state,
+ child: MouseRegion(
+ // 只认鼠标移动:键盘上下移动时列表滚动,不能让鼠标下面的那一行把选中抢走
+ onHover: (_) => state.select(index),
+ cursor: enabled ? SystemMouseCursors.click : MouseCursor.defer,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => state.chooseIndex(index),
+ onSecondaryTapUp: (d) => _menu(context, d.globalPosition),
+ child: Container(
+ margin: const EdgeInsets.symmetric(horizontal: Insets.xs),
+ padding: const EdgeInsets.symmetric(horizontal: Insets.sm),
+ decoration: BoxDecoration(
+ color: onAccent ? p.accent : (selected ? p.hover : Colors.transparent),
+ borderRadius: BorderRadius.circular(Radii.sm),
+ ),
+ child: Row(
+ children: [
+ SizedBox(
+ width: Platform.isMacOS ? 26 : 40,
+ child: number == null
+ ? null
+ : Text(number!, style: context.text.labelMedium?.copyWith(color: onAccent ? Colors.white : dim)),
+ ),
+ SizedBox(
+ width: 22,
+ height: 22,
+ child: thumb != null && thumb.isNotEmpty
+ ? ClipRRect(
+ borderRadius: BorderRadius.circular(3),
+ child: Image.file(File(thumb), fit: BoxFit.cover, cacheWidth: 64,
+ errorBuilder: (_, _, _) => Icon(kindIcon(r), size: 16, color: sub)),
+ )
+ : Icon(r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY ? AppIcons.arrowDownCircle : kindIcon(r),
+ size: 16, color: onAccent ? Colors.white : p.textDim),
+ ),
+ const SizedBox(width: Insets.sm),
+ Expanded(
+ child: Text(
+ recordTitle(r, query: state.query.trim().isEmpty ? null : state.query.trim()),
+ style: context.text.bodyMedium?.copyWith(color: fg),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (!favoritesTab && r.favorited) ...[
+ const SizedBox(width: Insets.xs),
+ Icon(AppIcons.starFill, size: 12, color: onAccent ? Colors.white : p.accent),
+ ],
+ const SizedBox(width: Insets.sm),
+ if (pending)
+ SizedBox(
+ width: 60,
+ child: LinearProgressIndicator(minHeight: 3, value: state.progressOf(r.id)),
+ )
+ else
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 190),
+ child: Text(meta, style: context.text.bodySmall?.copyWith(color: sub), maxLines: 1, overflow: TextOverflow.ellipsis),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _menu(BuildContext context, Offset at) async {
+ final l = context.l10n;
+ final r = record;
+ final favorited = r.favorite || r.favorited;
+ final choice = await showMenu<String>(
+ context: context,
+ position: RelativeRect.fromLTRB(at.dx, at.dy, at.dx, at.dy),
+ items: [
+ if (PickerState.selectable(r)) PopupMenuItem(value: 'copy', height: 30, child: Text(l.pickerCopyOnly)),
+ PopupMenuItem(value: 'favorite', height: 30, child: Text(favorited ? l.unfavoriteAction : l.favoriteAction)),
+ if (!r.favorite) PopupMenuItem(value: 'delete', height: 30, child: Text(l.deleteRecord)),
+ ],
+ );
+ switch (choice) {
+ case 'copy':
+ await state.choose(r, copyOnly: true);
+ case 'favorite':
+ await state.toggleFavorite(r);
+ case 'delete':
+ await state.delete(r);
+ }
+ }
+}
diff --git a/ui/lib/quick_paste_service.dart b/ui/lib/quick_paste_service.dart
new file mode 100644
index 0000000..dc887aa
--- /dev/null
+++ b/ui/lib/quick_paste_service.dart
@@ -0,0 +1,186 @@
+import 'dart:io';
+
+import 'background_service.dart';
+import 'hotkey.dart';
+
+/// 快捷粘贴窗口进程的登记。见 design/quick-paste-and-favorites.md 第 6.1 节。
+///
+/// Mac 上它是 App 包里单独的辅助程序 PasteFerryPicker.app,由界面登记成第二个 LaunchAgent:
+/// 不能让后台服务直接拉起它,系统按拉起它的进程记辅助功能权限,授权列表里会显示成后台服务。
+/// Windows、Linux 上快捷窗口由后台服务拉起(界面程序加 --picker),这里什么都不做。
+abstract class QuickPasteService {
+ factory QuickPasteService() => Platform.isMacOS ? MacQuickPasteService() : const _ManagedByDaemon();
+
+ /// App 里带着快捷窗口(开发构建没有)
+ bool get available;
+
+ /// 已登记,并且指向当前这个 App
+ Future<bool> installed();
+
+ /// 登记并启动。重复调用即为修复
+ Future<void> install();
+
+ /// 停止并取消登记
+ Future<void> uninstall();
+
+ /// 按当前的 App 重新拉起。用于 App 更新后
+ Future<void> restart();
+}
+
+class _ManagedByDaemon implements QuickPasteService {
+ const _ManagedByDaemon();
+ @override
+ bool get available => false;
+ @override
+ Future<bool> installed() async => true;
+ @override
+ Future<void> install() async {}
+ @override
+ Future<void> uninstall() async {}
+ @override
+ Future<void> restart() async {}
+}
+
+class MacQuickPasteService implements QuickPasteService {
+ MacQuickPasteService({String? executable, String? home})
+ : _executable = executable ?? Platform.resolvedExecutable,
+ _home = home ?? Platform.environment['HOME'] ?? '';
+
+ static const label = 'com.pasteferry.picker';
+ static const _appBundleId = 'com.pasteferry.app';
+
+ final String _executable;
+ final String _home;
+
+ /// `…/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 plistPath => '$_home/Library/LaunchAgents/$label.plist';
+ String get logPath => '$_home/Library/Logs/PasteFerry/picker.log';
+
+ @override
+ bool get available => File(helperBinary).existsSync() && !_bundle.startsWith('/Volumes/');
+
+ @override
+ Future<bool> installed() async {
+ final plist = 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;
+ }
+
+ @override
+ Future<void> install() async {
+ await _bootout();
+ 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]);
+ if (r.exitCode != 0) throw ServiceException('${r.stderr}'.trim());
+ }
+
+ @override
+ Future<void> uninstall() async {
+ await _bootout();
+ final plist = File(plistPath);
+ if (await plist.exists()) await plist.delete();
+ }
+
+ @override
+ Future<void> restart() async {
+ await Process.run('launchctl', ['kickstart', '-k', await _target()]);
+ }
+
+ Future<void> _bootout() async {
+ 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;
+ await Future<void>.delayed(const Duration(milliseconds: 250));
+ }
+ }
+
+ String? _uid;
+ Future<String> _domain() async {
+ _uid ??= '${(await Process.run('id', ['-u'])).stdout}'.trim();
+ return 'gui/$_uid';
+ }
+
+ Future<String> _target() async => '${await _domain()}/$label';
+
+ // 只在异常退出时重启:快捷粘贴被关掉时它自己正常退出,不该再被拉起来
+ 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>ProgramArguments</key>
+ <array>
+ <string>${_xml(helperBinary)}</string>
+ </array>
+ <key>RunAtLoad</key> <true/>
+ <key>KeepAlive</key>
+ <dict>
+ <key>SuccessfulExit</key> <false/>
+ </dict>
+ <key>ThrottleInterval</key> <integer>10</integer>
+ <key>LimitLoadToSessionType</key> <string>Aqua</string>
+ <key>StandardOutPath</key> <string>${_xml(logPath)}</string>
+ <key>StandardErrorPath</key> <string>${_xml(logPath)}</string>
+ <key>ProcessType</key> <string>Interactive</string>
+ <key>AssociatedBundleIdentifiers</key>
+ <array>
+ <string>$_appBundleId</string>
+ </array>
+</dict>
+</plist>
+''';
+
+ static String _xml(String s) => s.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
+}
+
+/// Linux Wayland 上没有全局快捷键门户时(如 Ubuntu 24.04 的 GNOME 46),
+/// 在 GNOME 的自定义快捷键里加一条,运行 `pasteferry --picker --toggle`:
+/// 它会交给已经在运行的快捷窗口显示或收起(见 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 bool get supported =>
+ Platform.isLinux && (Platform.environment['XDG_CURRENT_DESKTOP'] ?? '').toUpperCase().contains('GNOME');
+
+ /// 呼出快捷窗口的命令
+ 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 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',
+ 'backquote': 'grave',
+ };
+ 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))]) {
+ 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();
+ if (!current.contains(_path)) {
+ final next = [...current, _path].map((p) => "'$p'").join(', ');
+ final r = await Process.run('gsettings', ['set', _schema, 'custom-keybindings', '[$next]']);
+ if (r.exitCode != 0) throw ServiceException('${r.stderr}'.trim());
+ }
+ }
+}
diff --git a/ui/lib/records.dart b/ui/lib/records.dart
new file mode 100644
index 0000000..28d8eee
--- /dev/null
+++ b/ui/lib/records.dart
@@ -0,0 +1,98 @@
+import 'package:flutter/widgets.dart';
+
+import 'gen/pasteferry/v1/daemon.pb.dart';
+import 'i18n.dart';
+import 'icons.dart';
+import 'widgets/common.dart';
+
+/// 复制记录、收藏和快捷窗口共用的类型筛选:全部 · 文字 · 链接 · 图片 · 文件。
+/// 见 design/quick-paste-and-favorites.md 第 5 节。
+enum RecordFilter { all, text, link, image, file }
+
+extension RecordFilterX on RecordFilter {
+ bool matches(ClipRecord r) => switch (this) {
+ RecordFilter.all => true,
+ // 富文本也是文字,用户不关心它在剪贴板里是不是 HTML;整条是网址的归到「链接」
+ RecordFilter.text =>
+ (r.kind == ClipKind.CLIP_KIND_TEXT || r.kind == ClipKind.CLIP_KIND_HTML) && !r.isLink,
+ RecordFilter.link => r.isLink,
+ RecordFilter.image => r.kind == ClipKind.CLIP_KIND_IMAGE,
+ RecordFilter.file => r.kind == ClipKind.CLIP_KIND_FILE,
+ };
+
+ String label(AppLocalizations l) => switch (this) {
+ RecordFilter.all => l.filterAll,
+ RecordFilter.text => l.filterText,
+ RecordFilter.link => l.filterLink,
+ RecordFilter.image => l.filterImage,
+ RecordFilter.file => l.filterFile,
+ };
+}
+
+/// 按内容类型区分的图标:只靠形状区分,不靠颜色。
+IconData kindIcon(ClipRecord r) => switch (r.kind) {
+ _ when r.isLink => AppIcons.link,
+ ClipKind.CLIP_KIND_TEXT => AppIcons.textAlignLeft,
+ ClipKind.CLIP_KIND_HTML => AppIcons.docRichtext,
+ ClipKind.CLIP_KIND_IMAGE => AppIcons.photo,
+ // 单张图片文件也用图片图标,一眼看出点开能预览
+ ClipKind.CLIP_KIND_FILE when r.items.length == 1 && r.imageCount == 1 => AppIcons.photo,
+ ClipKind.CLIP_KIND_FILE when r.items.length > 1 => AppIcons.docOnDoc,
+ ClipKind.CLIP_KIND_FILE when r.items.isNotEmpty && r.items.first.isDir =>
+ AppIcons.folder,
+ ClipKind.CLIP_KIND_FILE => AppIcons.doc,
+ _ => AppIcons.questionCircle,
+ };
+
+/// 记录在列表里的标题。搜索时传入 [query]:一次复制了多个文件、搜到的又不是第一个时,
+/// 标题改用搜到的那个文件名打头,看得出为什么搜到了它。
+String recordTitle(ClipRecord r, {String? query}) {
+ // 图片和文件的标题按当前界面语言拼:后台服务存下的摘要是写入时的中文,不会跟着换语言
+ if (r.kind == ClipKind.CLIP_KIND_IMAGE) return appL10n.imageRecord;
+ if (r.kind != ClipKind.CLIP_KIND_FILE && r.textPreview.isNotEmpty) {
+ return r.textPreview.replaceAll('\n', ' ').trim();
+ }
+ if (r.items.isEmpty) return appL10n.emptyRecord;
+ if (r.items.length == 1) return r.items.first.name;
+ final q = query?.toLowerCase();
+ final lead = q == null ? null : r.items.where((i) => i.name.toLowerCase().contains(q)).firstOrNull;
+ return appL10n.itemsSummary((lead ?? r.items.first).name, r.items.length - 1, r.items.length);
+}
+
+/// 记录的来源:本机,或者「来自」哪台设备。
+String recordSource(ClipRecord r) => r.outgoing ? appL10n.thisDeviceShort : appL10n.fromDevice(r.originDeviceName);
+
+DateTime recordTime(ClipRecord r) => DateTime.fromMillisecondsSinceEpoch(r.createdAtUnix.toInt() * 1000);
+
+DateTime favoritedTime(ClipRecord r) => DateTime.fromMillisecondsSinceEpoch(r.favoritedAtUnix.toInt() * 1000);
+
+/// 列表里标题下面那一行:来源 · 大小 · 时间。收藏显示收藏时间。
+String recordMeta(ClipRecord r) => [
+ recordSource(r),
+ if (r.totalSize > 0) humanBytes(r.totalSize.toInt()),
+ r.favorite ? appL10n.favoritedAt(shortDate(favoritedTime(r))) : relativeTime(recordTime(r)),
+ ].join(' · ');
+
+/// 月日,今年以前的带上年份。
+String shortDate(DateTime t, {DateTime? now}) {
+ final n = now ?? DateTime.now();
+ final md = appL10n.monthDay(t.month, t.day);
+ return t.year == n.year ? md : '${t.year} $md';
+}
+
+/// 把 [text] 里所有不分大小写匹配 [query] 的片段套上 [mark] 样式。
+/// 转小写后长度变了的少数字符(如土耳其语的 İ)对不上位置,这时不标。
+List<TextSpan> highlightMatches(String text, String? query, TextStyle mark) {
+ final lower = text.toLowerCase();
+ final q = query?.toLowerCase() ?? '';
+ if (q.isEmpty || lower.length != text.length) return [TextSpan(text: text)];
+ final spans = <TextSpan>[];
+ var start = 0;
+ for (var i = lower.indexOf(q); i >= 0; i = lower.indexOf(q, start)) {
+ if (i > start) spans.add(TextSpan(text: text.substring(start, i)));
+ spans.add(TextSpan(text: text.substring(i, i + q.length), style: mark));
+ start = i + q.length;
+ }
+ if (start < text.length) spans.add(TextSpan(text: text.substring(start)));
+ return spans;
+}
diff --git a/ui/lib/widgets/common.dart b/ui/lib/widgets/common.dart
index e8c81c2..d5b11c5 100644
--- a/ui/lib/widgets/common.dart
+++ b/ui/lib/widgets/common.dart
@@ -108,12 +108,15 @@ class GroupSection extends StatelessWidget {
/// 设置项行:左侧标题与说明,右侧控件。
class SettingRow extends StatelessWidget {
- const SettingRow({super.key, required this.title, required this.child, this.description});
+ const SettingRow({super.key, required this.title, required this.child, this.description, this.descriptionColor});
final String title;
final String? description;
final Widget child;
+ /// 说明文字的颜色,出错时用红色;不给时用默认的次要文字色
+ final Color? descriptionColor;
+
@override
Widget build(BuildContext context) {
return ConstrainedBox(
@@ -130,7 +133,7 @@ class SettingRow extends StatelessWidget {
Text(title, style: context.text.labelLarge),
if (description != null) ...[
const SizedBox(height: 2),
- Text(description!, style: context.text.bodySmall),
+ Text(description!, style: context.text.bodySmall?.copyWith(color: descriptionColor)),
],
],
),
@@ -438,12 +441,15 @@ class AppMark extends StatelessWidget {
/// 可点击的图标按钮,悬停时出现浅色底。
class IconAction extends StatefulWidget {
- const IconAction({super.key, required this.icon, required this.tooltip, this.onTap});
+ const IconAction({super.key, required this.icon, required this.tooltip, this.onTap, this.color});
final IconData icon;
final String tooltip;
final VoidCallback? onTap;
+ /// 图标的颜色;不给时用次要文字色,悬停时变深。亮着的星标用强调色
+ final Color? color;
+
@override
State<IconAction> createState() => _IconActionState();
}
@@ -469,7 +475,7 @@ class _IconActionState extends State<IconAction> {
color: _hovered ? p.hover : Colors.transparent,
borderRadius: BorderRadius.circular(Radii.sm),
),
- child: Icon(widget.icon, size: 16, color: _hovered ? p.text : p.textDim),
+ child: Icon(widget.icon, size: 16, color: widget.color ?? (_hovered ? p.text : p.textDim)),
),
),
),
@@ -507,7 +513,9 @@ String relativeTime(DateTime t, {DateTime? now}) {
return l.monthDay(t.month, t.day);
}
-void showToast(BuildContext context, String message, {bool error = false}) {
+/// 底部的提示条。给了 [actionLabel] 时右边多一个按钮,比如取消收藏后的「撤销」。
+void showToast(BuildContext context, String message,
+ {bool error = false, String? actionLabel, VoidCallback? onAction}) {
final p = context.palette;
ScaffoldMessenger.of(context)
..hideCurrentSnackBar()
@@ -523,7 +531,10 @@ void showToast(BuildContext context, String message, {bool error = false}) {
Expanded(child: Text(message)),
],
),
- duration: const Duration(seconds: 3),
+ action: actionLabel == null || onAction == null
+ ? null
+ : SnackBarAction(label: actionLabel, onPressed: onAction),
+ duration: Duration(seconds: actionLabel == null ? 3 : 5),
width: 360,
));
}
diff --git a/ui/lib/widgets/favorite_actions.dart b/ui/lib/widgets/favorite_actions.dart
new file mode 100644
index 0000000..3636ac5
--- /dev/null
+++ b/ui/lib/widgets/favorite_actions.dart
@@ -0,0 +1,68 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+
+import '../app_state.dart';
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../i18n.dart';
+import '../platform.dart';
+import 'common.dart';
+
+/// 要整份复制、超过这个大小时先确认。见 design/quick-paste-and-favorites.md 第 3.2 节。
+const _confirmCopyBytes = 1 << 30;
+
+/// 收藏一条复制记录(另存一份),或取消收藏(放回复制记录的最上面,可以撤销)。
+/// [r] 是复制记录(看 favorited 决定收藏还是取消)或收藏本身(取消)。
+Future<void> toggleFavorite(BuildContext context, AppState state, ClipRecord r) async {
+ final l = context.l10n;
+ final remove = r.favorite || r.favorited;
+ try {
+ if (remove) {
+ final back = await state.setFavorite(r.id, false);
+ if (!context.mounted) return;
+ showToast(context, l.unfavoritedToast, actionLabel: l.undo, onAction: () async {
+ try {
+ await state.setFavorite(back.id, true);
+ } catch (e) {
+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);
+ }
+ });
+ return;
+ }
+ if (_needsFullCopy(r) && !await _confirmLargeCopy(context, r)) return;
+ final fav = await state.setFavorite(r.id, true);
+ if (!context.mounted) return;
+ if (fav.status == ClipStatus.CLIP_STATUS_FAILED) {
+ showToast(context, fav.error.isEmpty ? l.transferFailed : fav.error, error: true);
+ } else {
+ showToast(context, l.favoritedToast);
+ }
+ } catch (e) {
+ if (context.mounted) showToast(context, AppState.describeError(e), error: true);
+ }
+}
+
+/// 本机复制的大文件要整份复制。Mac 上的 APFS 写时复制几乎不占空间,不问;
+/// 从其他设备收到的在缓存里,用硬链接,也不问。
+bool _needsFullCopy(ClipRecord r) =>
+ !Platform.isMacOS &&
+ r.kind == ClipKind.CLIP_KIND_FILE &&
+ r.outgoing &&
+ r.totalSize.toInt() > _confirmCopyBytes;
+
+Future<bool> _confirmLargeCopy(BuildContext context, ClipRecord r) async {
+ final l = context.l10n;
+ final size = humanBytes(r.totalSize.toInt());
+ final ok = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.favoriteLargeTitle(size)),
+ content: Text(l.favoriteLargeBody(size, Wording.thisDeviceInText)),
+ actions: [
+ OutlinedButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ FilledButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.saveCopy)),
+ ],
+ ),
+ );
+ return ok == true;
+}
diff --git a/ui/lib/widgets/record_hover.dart b/ui/lib/widgets/record_hover.dart
new file mode 100644
index 0000000..089f5d5
--- /dev/null
+++ b/ui/lib/widgets/record_hover.dart
@@ -0,0 +1,367 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+
+import '../gen/pasteferry/v1/daemon.pb.dart';
+import '../i18n.dart';
+import '../records.dart';
+import '../theme.dart';
+import 'common.dart';
+
+/// 悬停提示框要的数据:完整的文字与图片在本机的位置。AppState 与快捷窗口各自提供。
+abstract interface class RecordDetails {
+ Future<ClipDetail> clipDetail(String clipId);
+ Future<GetImagePreviewResponse> imagePreview(String clipId, {int index = 0});
+}
+
+/// 鼠标在一行上停约 0.5 秒,弹出提示框显示完整内容:文字的全文、放大的图片、完整的文件列表。
+/// 主窗口的复制记录页、收藏页与快捷窗口共用,见 design/quick-paste-and-favorites.md 第 4 节。
+///
+/// 只认鼠标移动:用键盘上下移动时列表滚动,鼠标下面换了一行也不弹,免得一路闪。
+/// 提示框画在窗口里面、这一行的下面,下面放不下就放到上面;它不接鼠标,鼠标照样能移到别的行。
+class RecordHover extends StatefulWidget {
+ const RecordHover({super.key, required this.record, required this.details, required this.child});
+
+ final ClipRecord record;
+ final RecordDetails details;
+ final Widget child;
+
+ /// 鼠标停多久才弹出
+ static const delay = Duration(milliseconds: 500);
+
+ @override
+ State<RecordHover> createState() => _RecordHoverState();
+}
+
+class _RecordHoverState extends State<RecordHover> {
+ final _portal = OverlayPortalController();
+ final _link = LayerLink();
+ Timer? _timer;
+
+ @override
+ void dispose() {
+ _timer?.cancel();
+ super.dispose();
+ }
+
+ void _arm() {
+ if (_portal.isShowing) return;
+ _timer?.cancel();
+ _timer = Timer(RecordHover.delay, () {
+ if (mounted) _portal.show();
+ });
+ }
+
+ void _hide() {
+ _timer?.cancel();
+ if (_portal.isShowing) _portal.hide();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return CompositedTransformTarget(
+ link: _link,
+ child: OverlayPortal(
+ controller: _portal,
+ overlayChildBuilder: _card,
+ child: MouseRegion(
+ onHover: (_) => _arm(),
+ onExit: (_) => _hide(),
+ child: Listener(
+ // 点了这一行就收起来:要么粘贴了,要么打开了预览
+ onPointerDown: (_) => _hide(),
+ child: widget.child,
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _card(BuildContext context) {
+ final box = this.context.findRenderObject() as RenderBox?;
+ if (box == null || !box.attached) return const SizedBox.shrink();
+ final screen = MediaQuery.sizeOf(context);
+ final top = box.localToGlobal(Offset.zero);
+ const margin = 12.0;
+ const estimatedHeight = 300.0;
+ final below = screen.height - (top.dy + box.size.height) >= estimatedHeight + margin ||
+ top.dy < screen.height / 2;
+ final width = (screen.width - margin * 2).clamp(200.0, 460.0);
+ // 左边和这一行的文字对齐(让开类型图标),右边不出窗口
+ final dx = math.min(math.max(32.0, margin - top.dx), screen.width - margin - width - top.dx);
+ return CompositedTransformFollower(
+ link: _link,
+ showWhenUnlinked: false,
+ targetAnchor: below ? Alignment.bottomLeft : Alignment.topLeft,
+ followerAnchor: below ? Alignment.topLeft : Alignment.bottomLeft,
+ offset: Offset(dx, below ? 2 : -2),
+ child: Align(
+ alignment: below ? Alignment.topLeft : Alignment.bottomLeft,
+ child: IgnorePointer(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: width,
+ maxHeight: below ? screen.height - top.dy - box.size.height - margin : top.dy - margin,
+ ),
+ child: _HoverCard(record: widget.record, details: widget.details),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _HoverCard extends StatelessWidget {
+ const _HoverCard({required this.record, required this.details});
+
+ final ClipRecord record;
+ final RecordDetails details;
+
+ /// 文字最多显示几行
+ static const maxLines = 15;
+
+ @override
+ Widget build(BuildContext context) {
+ final p = context.palette;
+ final r = record;
+ final Widget body;
+ if (r.kind == ClipKind.CLIP_KIND_TEXT || r.kind == ClipKind.CLIP_KIND_HTML) {
+ body = _TextBody(record: r, details: details);
+ } else if (r.status != ClipStatus.CLIP_STATUS_READY) {
+ body = _FileList(record: r, details: details, notReceived: r.status == ClipStatus.CLIP_STATUS_REMOTE_ONLY);
+ } else if (r.imageCount > 0 && (r.kind == ClipKind.CLIP_KIND_IMAGE || r.items.length == 1)) {
+ body = _ImageBody(record: r, details: details);
+ } else {
+ body = _FileList(record: r, details: details);
+ }
+ return Material(
+ type: MaterialType.transparency,
+ child: Container(
+ padding: const EdgeInsets.all(Insets.md),
+ decoration: BoxDecoration(
+ color: p.surface,
+ borderRadius: BorderRadius.circular(Radii.md),
+ border: Border.all(color: p.border),
+ boxShadow: const [BoxShadow(color: Color(0x26000000), blurRadius: 16, offset: Offset(0, 4))],
+ ),
+ child: body,
+ ),
+ );
+ }
+}
+
+/// 最后一行:来源、完整的复制时间,以及大小或字数。
+class _Footer extends StatelessWidget {
+ const _Footer({required this.record, required this.extra});
+
+ final ClipRecord record;
+ final String? extra;
+
+ @override
+ Widget build(BuildContext context) {
+ final t = recordTime(record);
+ final hm = '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}';
+ return Padding(
+ padding: const EdgeInsets.only(top: Insets.sm),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Divider(height: 1, color: context.palette.border),
+ const SizedBox(height: Insets.sm),
+ Text(
+ [recordSource(record), '${shortDate(t)} $hm', if (extra?.isNotEmpty ?? false) extra!].join(' · '),
+ style: context.text.bodySmall,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _TextBody extends StatelessWidget {
+ const _TextBody({required this.record, required this.details});
+
+ final ClipRecord record;
+ final RecordDetails details;
+
+ @override
+ Widget build(BuildContext context) {
+ final l = context.l10n;
+ return FutureBuilder<ClipDetail>(
+ future: details.clipDetail(record.id),
+ builder: (context, snap) {
+ final d = snap.data;
+ final text = d?.text ?? record.textPreview;
+ final length = d?.textLength ?? text.runes.length;
+ final lines = '\n'.allMatches(text).length + 1;
+ final truncated = length > text.runes.length || lines > _HoverCard.maxLines;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: Text(
+ text,
+ style: context.text.bodyMedium,
+ maxLines: _HoverCard.maxLines,
+ overflow: TextOverflow.fade,
+ ),
+ ),
+ if (truncated)
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: Text(l.detailTruncated(length), style: context.text.bodySmall),
+ ),
+ _Footer(record: record, extra: l.detailChars(length)),
+ ],
+ );
+ },
+ );
+ }
+}
+
+class _ImageBody extends StatefulWidget {
+ const _ImageBody({required this.record, required this.details});
+
+ final ClipRecord record;
+ final RecordDetails details;
+
+ @override
+ State<_ImageBody> createState() => _ImageBodyState();
+}
+
+class _ImageBodyState extends State<_ImageBody> {
+ late final Future<(String, Size?)> _image = _load();
+
+ Future<(String, Size?)> _load() async {
+ final path = (await widget.details.imagePreview(widget.record.id)).path;
+ Size? size;
+ try {
+ // 只读文件头取尺寸,不解码整张图
+ final buffer = await ui.ImmutableBuffer.fromFilePath(path);
+ final desc = await ui.ImageDescriptor.encoded(buffer);
+ size = Size(desc.width.toDouble(), desc.height.toDouble());
+ desc.dispose();
+ buffer.dispose();
+ } catch (_) {}
+ return (path, size);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final r = widget.record;
+ return FutureBuilder<(String, Size?)>(
+ future: _image,
+ builder: (context, snap) {
+ final data = snap.data;
+ final size = data?.$2;
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 360, maxHeight: 240, minHeight: 60, minWidth: 120),
+ child: data == null
+ ? const SizedBox(width: 120, height: 60)
+ : ClipRRect(
+ borderRadius: BorderRadius.circular(Radii.sm),
+ child: Image.file(
+ File(data.$1),
+ fit: BoxFit.contain,
+ cacheWidth: 720,
+ errorBuilder: (_, _, _) => const SizedBox(width: 120, height: 60),
+ ),
+ ),
+ ),
+ if (r.kind == ClipKind.CLIP_KIND_FILE)
+ Padding(
+ padding: const EdgeInsets.only(top: Insets.sm),
+ child: Text(r.items.first.name, style: context.text.labelLarge, maxLines: 2, overflow: TextOverflow.ellipsis),
+ ),
+ _Footer(
+ record: r,
+ extra: [
+ if (size != null) '${size.width.toInt()} × ${size.height.toInt()}',
+ if (r.totalSize > 0) humanBytes(r.totalSize.toInt()),
+ ].join(' · '),
+ ),
+ ],
+ );
+ },
+ );
+ }
+}
+
+class _FileList extends StatelessWidget {
+ const _FileList({required this.record, required this.details, this.notReceived = false});
+
+ final ClipRecord record;
+ final RecordDetails details;
+ final bool notReceived;
+
+ static const maxItems = 10;
+
+ @override
+ Widget build(BuildContext context) {
+ final l = context.l10n;
+ final r = record;
+ final shown = r.items.take(maxItems).toList();
+ return FutureBuilder<ClipDetail>(
+ // 本机复制的文件显示所在的文件夹
+ future: r.outgoing ? details.clipDetail(r.id) : null,
+ builder: (context, snap) {
+ final folder = _folderOf(snap.data?.sourcePaths ?? const []);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final it in shown)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 1),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(it.isDir ? '${it.name}/' : it.name,
+ style: context.text.bodyMedium, maxLines: 1, overflow: TextOverflow.ellipsis),
+ ),
+ if (it.size > 0 && !it.isDir) ...[
+ const SizedBox(width: Insets.md),
+ Text(humanBytes(it.size.toInt()), style: context.text.bodySmall),
+ ],
+ ],
+ ),
+ ),
+ if (r.items.length > maxItems)
+ Text(l.detailMoreFiles(r.items.length - maxItems), style: context.text.bodySmall),
+ if (notReceived)
+ Padding(
+ padding: const EdgeInsets.only(top: Insets.xs),
+ child: Text(l.detailReceiveFirst, style: context.text.bodySmall),
+ ),
+ _Footer(
+ record: r,
+ extra: [
+ ?folder,
+ if (r.totalSize > 0) l.detailTotalSize(humanBytes(r.totalSize.toInt())),
+ ].join(' · '),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
+ /// 第一个文件所在的文件夹,用户目录写成 ~。
+ static String? _folderOf(List<String> paths) {
+ if (paths.isEmpty) return null;
+ var dir = File(paths.first).parent.path;
+ final home = Platform.environment[Platform.isWindows ? 'USERPROFILE' : 'HOME'];
+ if (home != null && home.isNotEmpty && dir.startsWith(home)) dir = '~${dir.substring(home.length)}';
+ return dir;
+ }
+}
diff --git a/ui/test/favorites_test.dart b/ui/test/favorites_test.dart
new file mode 100644
index 0000000..bf78224
--- /dev/null
+++ b/ui/test/favorites_test.dart
@@ -0,0 +1,215 @@
+import 'package:fixnum/fixnum.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:pasteferry_ui/app_state.dart';
+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';
+import 'package:pasteferry_ui/main.dart';
+import 'package:pasteferry_ui/widgets/record_hover.dart';
+
+/// 不连后台服务:收藏与取消收藏按后台服务的规则在本地模拟,完整内容按测试给的回答。
+class _FavState extends AppState {
+ final calls = <(String, bool)>[];
+ final detailCalls = <String>[];
+ int _next = 0;
+
+ @override
+ Future<ClipRecord> setFavorite(String clipId, bool favorite) async {
+ calls.add((clipId, favorite));
+ final now = Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000);
+ if (favorite) {
+ final src = records.firstWhere((r) => r.id == clipId);
+ final fav = src.deepCopy()
+ ..id = 'fav-${_next++}'
+ ..favorite = true
+ ..favorited = false
+ ..favoritedAtUnix = now + _next;
+ debugEvent(Event(clipAdded: src.deepCopy()..favorited = true));
+ debugEvent(Event(clipAdded: fav));
+ return fav;
+ }
+ // 取消收藏:收藏放回复制记录的最上面,原记录合并掉
+ final fav = favorites.firstWhere((r) => r.id == clipId || r.id == 'fav-of-$clipId', orElse: () => favorites.first);
+ final back = fav.deepCopy()
+ ..favorite = false
+ ..favoritedAtUnix = Int64(0)
+ ..createdAtUnix = now;
+ for (final r in records.where((r) => r.favorited).toList()) {
+ debugEvent(Event(clipRemoved: r.id));
+ }
+ debugEvent(Event(clipAdded: back));
+ return back;
+ }
+
+ @override
+ Future<ClipDetail> requestClipDetail(String clipId) async {
+ detailCalls.add(clipId);
+ return ClipDetail(text: 'SELECT o.id\nFROM orders o\nWHERE o.status = \'paid\';', textLength: 42);
+ }
+}
+
+final _now = Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000);
+
+final _text = ClipRecord(
+ id: 'text',
+ kind: ClipKind.CLIP_KIND_TEXT,
+ status: ClipStatus.CLIP_STATUS_READY,
+ textPreview: 'SELECT o.id FROM orders o WHERE o.status = …',
+ outgoing: true,
+ createdAtUnix: _now - 60,
+);
+final _link = ClipRecord(
+ id: 'link',
+ kind: ClipKind.CLIP_KIND_TEXT,
+ status: ClipStatus.CLIP_STATUS_READY,
+ textPreview: 'https://pasteferry.cc/download/',
+ isLink: true,
+ outgoing: true,
+ createdAtUnix: _now - 120,
+);
+final _image = ClipRecord(
+ id: 'image',
+ kind: ClipKind.CLIP_KIND_IMAGE,
+ status: ClipStatus.CLIP_STATUS_READY,
+ originDeviceName: 'Windows PC',
+ imageCount: 1,
+ totalSize: Int64(1 << 20),
+ createdAtUnix: _now - 180,
+);
+
+_FavState _seed({List<ClipRecord> favorites = const []}) => _FavState()
+ ..debugSeed(
+ status: Status(signalingConnected: true, version: '2.4.0'),
+ config: Config(language: 'zh-Hans', historyTtlSeconds: Int64(3 * 86400)),
+ self: Device(id: 'self', name: 'MacBook Pro'),
+ records: [_text, _link, _image],
+ favorites: favorites,
+ );
+
+Future<TestGesture> _hover(WidgetTester tester, Finder target) async {
+ final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await gesture.addPointer(location: Offset.zero);
+ addTearDown(gesture.removePointer);
+ await gesture.moveTo(tester.getCenter(target));
+ await tester.pump();
+ // 鼠标在行里动一下才开始计时
+ await gesture.moveTo(tester.getCenter(target) + const Offset(4, 0));
+ await tester.pump();
+ return gesture;
+}
+
+void main() {
+ testWidgets('「链接」只列出整条是网址的记录,「文本」里不再有它', (tester) async {
+ await tester.pumpWidget(PasteFerryApp(state: _seed()));
+ await tester.pump();
+ await tester.tap(find.text('链接'));
+ await tester.pump();
+ expect(find.text('https://pasteferry.cc/download/'), findsOneWidget);
+ expect(find.textContaining('SELECT'), findsNothing);
+
+ await tester.tap(find.text('文本'));
+ await tester.pump();
+ expect(find.textContaining('SELECT'), findsOneWidget);
+ expect(find.text('https://pasteferry.cc/download/'), findsNothing);
+ });
+
+ testWidgets('点星标收藏:出现在收藏页,原记录的星标一直亮着', (tester) async {
+ final state = _seed();
+ await tester.pumpWidget(PasteFerryApp(state: state));
+ await tester.pump();
+
+ await _hover(tester, find.textContaining('SELECT'));
+ await tester.tap(find.byTooltip('收藏').first);
+ await tester.pump();
+ expect(state.calls, [('text', true)]);
+ expect(find.text('已收藏'), findsOneWidget);
+ expect(state.records.firstWhere((r) => r.id == 'text').favorited, isTrue);
+ expect(state.favorites.single.textPreview, _text.textPreview);
+
+ // 鼠标移开,亮着的星标还在
+ await tester.tap(find.text('收藏').first); // 侧边栏
+ await tester.pumpAndSettle();
+ expect(find.textContaining('SELECT'), findsOneWidget);
+ expect(find.textContaining('不会被自动清理'), findsOneWidget);
+ expect(find.byTooltip('取消收藏'), findsOneWidget);
+ });
+
+ testWidgets('在收藏页取消收藏:放回复制记录,可以撤销', (tester) async {
+ final fav = _text.deepCopy()
+ ..id = 'fav-of-text'
+ ..favorite = true
+ ..favoritedAtUnix = _now;
+ final state = _seed(favorites: [fav]);
+ await tester.pumpWidget(PasteFerryApp(state: state));
+ await tester.pump();
+ await tester.tap(find.text('收藏').first);
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byTooltip('取消收藏'));
+ await tester.pump();
+ expect(state.calls.last, ('fav-of-text', false));
+ expect(state.favorites, isEmpty);
+ expect(state.records.first.id, 'fav-of-text');
+ expect(find.text('已放回复制记录'), findsOneWidget);
+ expect(find.text('还没有收藏'), findsOneWidget);
+ // 收藏里没有删除
+ expect(find.byTooltip('删除这条记录'), findsNothing);
+
+ await tester.pump(const Duration(milliseconds: 500)); // 提示条滑进来
+ await tester.tap(find.text('撤销'));
+ await tester.pump();
+ expect(state.calls.last, ('fav-of-text', true));
+ });
+
+ testWidgets('鼠标停一会儿显示完整内容,移开就消失', (tester) async {
+ final state = _seed();
+ await tester.pumpWidget(PasteFerryApp(state: state));
+ await tester.pump();
+
+ // 列表里的预览没有 'paid',只有完整内容里有
+ final gesture = await _hover(tester, find.textContaining('SELECT'));
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.textContaining("'paid'"), findsNothing, reason: '还没到时间');
+ await tester.pump(RecordHover.delay);
+ await tester.pump();
+ expect(find.textContaining("'paid'"), findsOneWidget);
+ expect(state.detailCalls, ['text']);
+ expect(find.textContaining('42 字'), findsOneWidget);
+
+ await gesture.moveTo(const Offset(5, 5));
+ await tester.pump();
+ expect(find.textContaining("'paid'"), findsNothing);
+ });
+
+ testWidgets('清空记录时说明收藏会保留', (tester) async {
+ final fav = _text.deepCopy()
+ ..id = 'fav'
+ ..favorite = true;
+ await tester.pumpWidget(PasteFerryApp(state: _seed(favorites: [fav])));
+ await tester.pump();
+ await tester.tap(find.byTooltip('清空记录'));
+ await tester.pumpAndSettle();
+ expect(find.textContaining('已收藏的 1 条会保留'), findsOneWidget);
+ });
+
+ test('事件按 favorite 分到复制记录或收藏,取消收藏的同一条换过去', () {
+ final state = _seed();
+ final fav = _image.deepCopy()
+ ..id = 'f1'
+ ..favorite = true
+ ..favoritedAtUnix = _now;
+ state.debugEvent(Event(clipAdded: fav));
+ expect(state.favorites.map((r) => r.id), ['f1']);
+ expect(state.records.map((r) => r.id), isNot(contains('f1')));
+
+ state.debugEvent(Event(clipAdded: fav.deepCopy()
+ ..favorite = false
+ ..createdAtUnix = _now + 10));
+ expect(state.favorites, isEmpty);
+ expect(state.records.first.id, 'f1', reason: '取消收藏后在复制记录的最上面');
+
+ state.debugEvent(Event(clipRemoved: 'f1'));
+ expect(state.records.map((r) => r.id), isNot(contains('f1')));
+ });
+}
diff --git a/ui/test/hotkey_test.dart b/ui/test/hotkey_test.dart
new file mode 100644
index 0000000..7302498
--- /dev/null
+++ b/ui/test/hotkey_test.dart
@@ -0,0 +1,46 @@
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:pasteferry_ui/hotkey.dart';
+
+void main() {
+ // 写法与后台服务的 config.NormalizeHotkey 一致,见 client-core/internal/config/hotkey_test.go
+ test('解析设置里存的快捷键', () {
+ expect(Hotkey.parse(''), Hotkey.fallback);
+ expect(Hotkey.parse('alt+v')!.canonical, 'alt+v');
+ expect(Hotkey.parse('Shift+Ctrl+V')!.canonical, 'ctrl+shift+v');
+ expect(Hotkey.parse('cmd+option+space')!.canonical, 'alt+meta+space');
+ expect(Hotkey.parse('f9')!.canonical, 'f9');
+ for (final bad in ['v', 'alt', 'alt+alt+v', 'hyper+v', 'alt+vv', 'f0', 'f25']) {
+ expect(Hotkey.parse(bad), isNull, reason: bad);
+ }
+ });
+
+ test('等于默认值时存空字符串', () {
+ expect(Hotkey.parse('alt+v')!.setting, '');
+ expect(Hotkey.parse('ctrl+alt+v')!.setting, 'ctrl+alt+v');
+ });
+
+ test('Mac 上用符号显示,其他平台用键名', () {
+ final h = Hotkey.parse('ctrl+alt+shift+meta+v')!;
+ expect(h.display(mac: true), '⌃⌥⇧⌘V');
+ expect(Hotkey.parse('alt+v')!.display(mac: true), '⌥V');
+ expect(Hotkey.parse('alt+v')!.display(mac: false), 'Alt+V');
+ expect(Hotkey.parse('ctrl+comma')!.display(mac: false), 'Ctrl+,');
+ expect(Hotkey.parse('alt+f9')!.display(mac: true), '⌥F9');
+ });
+
+ test('录制时按下的键换成快捷键', () {
+ expect(Hotkey.fromKey(LogicalKeyboardKey.keyV, PhysicalKeyboardKey.keyV, {'alt'})!.canonical, 'alt+v');
+ // Mac 上按着 ⌥ 时逻辑键可能是 √,退回按物理位置认
+ expect(
+ Hotkey.fromKey(const LogicalKeyboardKey(0x221a), PhysicalKeyboardKey.keyV, {'alt'})!.canonical,
+ 'alt+v',
+ );
+ expect(Hotkey.fromKey(LogicalKeyboardKey.digit3, PhysicalKeyboardKey.digit3, {'ctrl', 'shift'})!.canonical,
+ 'ctrl+shift+3');
+ expect(Hotkey.fromKey(LogicalKeyboardKey.altLeft, PhysicalKeyboardKey.altLeft, {'alt'}), isNull);
+ expect(Hotkey.fromKey(LogicalKeyboardKey.keyV, PhysicalKeyboardKey.keyV, {})!.usable, isFalse);
+ expect(Hotkey.fromKey(LogicalKeyboardKey.f9, PhysicalKeyboardKey.f9, {})!.usable, isTrue);
+ });
+}
diff --git a/ui/test/i18n_test.dart b/ui/test/i18n_test.dart
index 6e1e787..f795a1e 100644
--- a/ui/test/i18n_test.dart
+++ b/ui/test/i18n_test.dart
@@ -61,6 +61,33 @@ AppState _demo(String language, {LinkState link = LinkState.online, ServiceState
items: [ClipItem(name: 'report.key'), ClipItem(name: 'notes.txt')],
),
],
+ favorites: [
+ ClipRecord(
+ id: 'fav',
+ kind: ClipKind.CLIP_KIND_TEXT,
+ favorite: true,
+ textPreview: 'https://pasteferry.cc/download/',
+ isLink: true,
+ outgoing: true,
+ totalSize: Int64(31),
+ ),
+ ClipRecord(
+ id: 'saving',
+ kind: ClipKind.CLIP_KIND_FILE,
+ favorite: true,
+ status: ClipStatus.CLIP_STATUS_FAILED,
+ error: '源设备当前不可达',
+ originDeviceName: 'MacBook Air',
+ items: [ClipItem(name: 'report.key')],
+ ),
+ ],
+ // 快捷键被占用、还没授予辅助功能:设置页上要显示的东西最多的情况
+ quickPaste: QuickPasteStatus(
+ running: true,
+ hotkey: 'alt+v',
+ hotkeyError: 'in_use',
+ pasteUnavailableReason: 'not_trusted',
+ ),
);
void main() {
@@ -151,12 +178,17 @@ void main() {
testWidgets('三个页面', (tester) async {
final l = await open(tester, _demo(language));
+ await tester.tap(find.text(l.navFavorites).first);
+ await tester.pump();
+ expect(find.text('https://pasteferry.cc/download/'), findsOneWidget);
await tester.tap(find.text(l.navDevices).first);
await tester.pump();
expect(find.text(l.pairedDevices), findsOneWidget);
await tester.tap(find.text(l.navSettings).first);
await tester.pump();
await tester.dragUntilVisible(find.text(l.language), find.byType(ListView), const Offset(0, -100));
+ await tester.dragUntilVisible(find.text(l.quickPasteAccessibility), find.byType(ListView), const Offset(0, -100));
+ await tester.dragUntilVisible(find.text(l.favoritesUsage), find.byType(ListView), const Offset(0, -100));
await tester.dragUntilVisible(find.text(l.about), find.byType(ListView), const Offset(0, -200));
});
diff --git a/ui/test/picker_test.dart b/ui/test/picker_test.dart
new file mode 100644
index 0000000..f4a8604
--- /dev/null
+++ b/ui/test/picker_test.dart
@@ -0,0 +1,260 @@
+import 'package:fixnum/fixnum.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:pasteferry_ui/gen/pasteferry/v1/daemon.pb.dart';
+import 'package:pasteferry_ui/picker/picker_host.dart';
+import 'package:pasteferry_ui/picker/picker_state.dart';
+import 'package:pasteferry_ui/picker/picker_view.dart';
+
+const _channel = MethodChannel('pasteferry/picker');
+
+/// 不连后台服务:放进剪贴板、下载、收藏都记下来。
+class _TestPicker extends PickerState {
+ _TestPicker() : super(host: PickerHost(_channel));
+
+ final applied = <(String, bool)>[];
+ final fetched = <String>[];
+ final favorited = <(String, bool)>[];
+ final searches = <(String, PickerTab)>[];
+
+ @override
+ Future<void> requestApply(String id, bool plain) async => applied.add((id, plain));
+
+ @override
+ Future<void> requestFetch(String id) async => fetched.add(id);
+
+ @override
+ Future<void> requestFavorite(String id, bool favorite) async => favorited.add((id, favorite));
+
+ @override
+ Future<ListHistoryResponse> requestSearch(String query, PickerTab tab) async {
+ searches.add((query, tab));
+ return ListHistoryResponse(searched: false);
+ }
+
+ @override
+ Future<ClipDetail> clipDetail(String clipId) async => ClipDetail(text: 'detail', textLength: 6);
+
+ @override
+ Future<GetImagePreviewResponse> imagePreview(String clipId, {int index = 0}) async => GetImagePreviewResponse();
+}
+
+final _now = Int64(DateTime.now().millisecondsSinceEpoch ~/ 1000);
+
+ClipRecord _text(String id, String text, {int ago = 0, bool link = false}) => ClipRecord(
+ id: id,
+ kind: ClipKind.CLIP_KIND_TEXT,
+ status: ClipStatus.CLIP_STATUS_READY,
+ textPreview: text,
+ isLink: link,
+ outgoing: true,
+ createdAtUnix: _now - ago,
+ );
+
+final _records = [
+ _text('a', '会议改到周四下午 3 点', ago: 1),
+ _text('b', 'https://github.com/baiyuze/pasteferry', ago: 60, link: true),
+ _text('c', 'docker compose up -d --build', ago: 3600),
+ ClipRecord(
+ id: 'big',
+ kind: ClipKind.CLIP_KIND_FILE,
+ status: ClipStatus.CLIP_STATUS_REMOTE_ONLY,
+ originDeviceName: 'MacBook Air',
+ items: [ClipItem(name: 'PasteFerry.dmg', size: Int64(812 << 20))],
+ totalSize: Int64(812 << 20),
+ createdAtUnix: _now - 7200,
+ ),
+];
+
+final _favorite = _text('f1', '收货地址:上海市徐汇区', ago: 86400)
+ ..favorite = true
+ ..favoritedAtUnix = _now;
+
+void main() {
+ late List<MethodCall> calls;
+
+ setUp(() {
+ calls = [];
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(_channel, (c) async {
+ calls.add(c);
+ return switch (c.method) {
+ 'commit' => {'pasted': true, 'reason': ''},
+ 'pasteStatus' => {'available': true, 'reason': ''},
+ _ => null,
+ };
+ });
+ });
+
+ Future<_TestPicker> open(WidgetTester tester, {Config? config, PasteStatus? paste}) async {
+ final view = tester.view;
+ view.physicalSize = const Size(560, 460);
+ view.devicePixelRatio = 1;
+ addTearDown(view.reset);
+ final s = _TestPicker()
+ ..debugSeed(
+ config: config ?? Config(language: 'zh-Hans'),
+ records: _records,
+ favorites: [_favorite],
+ paste: paste ?? const PasteStatus(available: true, reason: ''),
+ );
+ await tester.pumpWidget(PickerApp(state: s));
+ await tester.pump();
+ return s;
+ }
+
+ List<MethodCall> commits() => calls.where((c) => c.method == 'commit').toList();
+
+ testWidgets('前 9 条标序号,按数字直接粘贴那一条', (tester) async {
+ final s = await open(tester);
+ expect(find.text('1'), findsOneWidget);
+ expect(find.text('4'), findsOneWidget);
+ // 「收藏」既是页签,也是底栏 ⌘D 的说明
+ for (final t in ['全部', '文本', '链接', '图片', '文件', '收藏']) {
+ expect(find.text(t), findsWidgets, reason: t);
+ }
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.digit2);
+ await tester.pump();
+ expect(s.applied, [('b', false)]);
+ expect(commits().single.arguments, {'paste': true});
+ });
+
+ testWidgets('搜索时数字是打字,序号变成 ⌘1……', (tester) async {
+ final s = await open(tester);
+ await tester.enterText(find.byType(TextField), 'docker 2');
+ await tester.pump();
+ expect(s.applied, isEmpty);
+ await tester.enterText(find.byType(TextField), 'docker');
+ await tester.pump();
+ expect(find.text('⌘1'), findsOneWidget);
+ expect(find.textContaining('docker compose'), findsOneWidget);
+ expect(find.textContaining('会议'), findsNothing);
+ // 停顿后在当前页签里搜全部历史
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(s.searches.last, ('docker', PickerTab.all));
+ });
+
+ testWidgets('上下键移动选择,回车粘贴,⇧回车纯文本,⌘回车只复制', (tester) async {
+ final s = await open(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(s.selected, 2);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(s.applied.last, ('c', false));
+ expect(commits().last.arguments, {'paste': true});
+
+ // 选中后会回到第一条
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.pump();
+ expect(s.applied.last, ('a', true));
+
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(commits().last.arguments, {'paste': false});
+ });
+
+ testWidgets('Tab 切换页签,「链接」只有网址,「收藏」里 ⌘D 是取消收藏', (tester) async {
+ final s = await open(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(s.tab, PickerTab.link);
+ expect(find.textContaining('github.com'), findsOneWidget);
+ expect(find.textContaining('会议'), findsNothing);
+
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.pump();
+ expect(s.tab, PickerTab.favorites);
+ expect(find.textContaining('收货地址'), findsOneWidget);
+ expect(find.textContaining('取消收藏(放回复制记录)'), findsOneWidget);
+
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyD);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+ await tester.pump();
+ expect(s.favorited, [('f1', false)]);
+ });
+
+ testWidgets('Esc 先清空搜索,再按一次收起窗口', (tester) async {
+ final s = await open(tester);
+ await tester.enterText(find.byType(TextField), 'docker');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(s.query, '');
+ expect(calls.where((c) => c.method == 'hide'), isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(calls.where((c) => c.method == 'hide'), hasLength(1));
+ });
+
+ testWidgets('设置里选了只复制:选中后不模拟粘贴,底栏写明要按 ⌘V', (tester) async {
+ final s = await open(tester, config: Config(language: 'zh-Hans', quickPasteCopyOnly: true));
+ expect(find.text('选中后按 ⌘V 粘贴'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.digit1);
+ await tester.pump();
+ expect(s.applied.single.$1, 'a');
+ expect(commits().single.arguments, {'paste': false});
+ });
+
+ testWidgets('没授予辅助功能:底栏提示并给出授权按钮', (tester) async {
+ await open(tester, paste: const PasteStatus(available: false, reason: 'not_trusted'));
+ expect(find.textContaining('授予「辅助功能」权限后可直接粘贴'), findsOneWidget);
+ await tester.tap(find.text('去授权'));
+ await tester.pump();
+ expect(calls.map((c) => c.method), contains('requestPermission'));
+ });
+
+ testWidgets('没下载的大文件:先下载,下完放进剪贴板再粘贴', (tester) async {
+ final s = await open(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.digit4);
+ await tester.pump();
+ expect(s.fetched, ['big']);
+ expect(s.applied, isEmpty);
+ expect(find.text('正在下载,下完自动粘贴'), findsOneWidget);
+
+ s.debugEvent(Event(clipUpdated: _records[3].deepCopy()..status = ClipStatus.CLIP_STATUS_READY));
+ await tester.pump();
+ expect(s.applied, [('big', false)]);
+ expect(commits().single.arguments, {'paste': true});
+ });
+
+ testWidgets('正在用输入法打字时,数字和回车交给输入法', (tester) async {
+ final s = await open(tester);
+ final field = tester.widget<TextField>(find.byType(TextField));
+ field.controller!.value = const TextEditingValue(
+ text: 'hui',
+ selection: TextSelection.collapsed(offset: 3),
+ composing: TextRange(start: 0, end: 3),
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.digit1);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(s.applied, isEmpty);
+ });
+
+ testWidgets('每次呼出都从「全部」、第一条、空搜索开始', (tester) async {
+ final s = await open(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.enterText(find.byType(TextField), 'abc');
+ await tester.pump();
+ s.debugShow();
+ await tester.pump();
+ expect(s.tab, PickerTab.all);
+ expect(s.query, '');
+ expect(tester.widget<TextField>(find.byType(TextField)).controller!.text, '');
+ });
+}
diff --git a/ui/tool/l10n/strings.py b/ui/tool/l10n/strings.py
index 8a2cf21..badd47e 100644
--- a/ui/tool/l10n/strings.py
+++ b/ui/tool/l10n/strings.py
@@ -20,6 +20,7 @@ S = [
("navHistory", "History", "复制记录", "履歴", "複製記錄", "複製記錄"),
("navDevices", "Devices", "设备", "デバイス", "裝置", "裝置"),
("navSettings", "Settings", "设置", "設定", "設定", "設定"),
+ ("navFavorites", "Favorites", "收藏", "お気に入り", "收藏", "收藏"),
("linkConnecting", "Connecting…", "正在连接…", "接続中…", "正在連線…", "正在連線…"),
("linkServiceNotRunning", "Service not running", "后台服务未运行", "サービス停止中", "背景服務未執行", "背景服務未在執行"),
("linkLanMode", "Looking for devices on this network", "在局域网中查找设备", "このネットワークでデバイスを探しています", "在區域網路中尋找裝置", "在區域網絡中尋找裝置"),
@@ -74,6 +75,7 @@ S = [
("filterText", "Text", "文本", "テキスト", "文字", "文字"),
("filterImage", "Images", "图片", "画像", "圖片", "圖片"),
("filterFile", "Files", "文件", "ファイル", "檔案", "檔案"),
+ ("filterLink", "Links", "链接", "リンク", "連結", "連結"),
("historyClearTooltip", "Clear history", "清空记录", "履歴を消去", "清空記錄", "清除記錄"),
("historyEmptyTitle", "Nothing here yet", "还没有记录", "まだ履歴がありません", "還沒有記錄", "仍未有記錄"),
("historyEmptyFilteredTitle", "Nothing of this kind", "没有这一类的记录", "この種類の履歴はありません", "沒有這一類的記錄", "沒有這一類的記錄"),
@@ -106,6 +108,69 @@ S = [
("searchEmptyTitle", "No matches for “{query}”", "没有找到「{query}」", "「{query}」は見つかりません", "找不到「{query}」", "找不到「{query}」"),
("searchEmptyBody", "Search looks through copied text and the names of copied files.", "搜索的是复制过的文字和文件名。", "コピーしたテキストとファイル名から検索します。", "搜尋範圍是複製過的文字和檔名。", "搜尋範圍是複製過的文字和檔案名稱。"),
+ # ── 收藏:另存一份、不会被自动清理,取消收藏时放回复制记录。见 design/quick-paste-and-favorites.md ──
+ ("favoriteAction", "Add to favorites", "收藏", "お気に入りに追加", "收藏", "收藏"),
+ ("unfavoriteAction", "Remove from favorites", "取消收藏", "お気に入りから外す", "取消收藏", "取消收藏"),
+ ("favoritedToast", "Added to Favorites", "已收藏", "お気に入りに追加しました", "已收藏", "已收藏"),
+ ("unfavoritedToast", "Moved back to History", "已放回复制记录", "履歴に戻しました", "已放回複製記錄", "已放回複製記錄"),
+ ("undo", "Undo", "撤销", "元に戻す", "復原", "復原"),
+ ("favoriteSaving", "Saving…", "正在保存…", "保存中…", "正在儲存…", "正在儲存…"),
+ ("favoritedAt", "Saved {date}", "收藏于 {date}", "{date} に保存", "收藏於 {date}", "收藏於 {date}"),
+ ("favoritesSubtitle", "{count, plural, =1{1 item} other{{count} items}} · never cleaned up · up to {size}", "{count} 条 · 不会被自动清理 · 最多占用 {size}", "{count} 件・自動では削除されません・最大 {size}", "{count} 筆 · 不會被自動清除 · 最多佔用 {size}", "{count} 條 · 不會被自動清理 · 最多佔用 {size}"),
+ ("favoritesEmptyTitle", "No favorites yet", "还没有收藏", "お気に入りはまだありません", "還沒有收藏", "仍未有收藏"),
+ ("favoritesEmptyBody", "Star an item in History to keep a copy here. Favorites are never cleaned up automatically.", "在复制记录里点星标,就会在这里另存一份。收藏不会被自动清理。", "履歴で星をクリックすると、ここにコピーが保存されます。お気に入りは自動では削除されません。", "在複製記錄裡點星號,就會在這裡另存一份。收藏不會被自動清除。", "在複製記錄裏按星號,就會在這裏另存一份。收藏不會被自動清理。"),
+ ("favoritesSearchHint", "Search favorites", "搜索收藏", "お気に入りを検索", "搜尋收藏", "搜尋收藏"),
+ ("favoriteLargeTitle", "Save a copy of {size}?", "另存一份 {size} 的内容?", "{size} のコピーを保存しますか?", "要另存一份 {size} 的內容嗎?", "另存一份 {size} 的內容?"),
+ ("favoriteLargeBody", "A favorite keeps its own copy, so changing or deleting the original files won't affect it. This uses {size} on {device}.", "收藏会另存一份,原文件之后改动或删除都不影响收藏。这会占用{device}上 {size} 的空间。", "お気に入りは独自のコピーを保存するため、元のファイルを変更・削除しても影響を受けません。{device}の {size} を使用します。", "收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用{device}上 {size} 的空間。", "收藏會另存一份,原檔案之後改動或刪除都不影響收藏。這會佔用{device}上 {size} 的空間。"),
+ ("saveCopy", "Save copy", "另存", "保存", "另存", "另存"),
+ ("clearKeepsFavorites", "{count, plural, =1{Your 1 favorite stays.} other{Your {count} favorites stay.}}", "已收藏的 {count} 条会保留。", "お気に入りの {count} 件は残ります。", "已收藏的 {count} 筆會保留。", "已收藏的 {count} 條會保留。"),
+ ("favoritesUsage", "Favorites", "收藏占用", "お気に入りの使用量", "收藏佔用", "收藏佔用"),
+ ("favoritesUsageDesc", "Favorites are never cleaned up, whatever the settings above", "收藏不受上面两项的限制,不会被自动清理", "お気に入りは上の設定にかかわらず自動では削除されません", "收藏不受上面兩項的限制,不會被自動清除", "收藏不受上面兩項的限制,不會被自動清理"),
+ ("upToSize", "Up to {size}", "最多 {size}", "最大 {size}", "最多 {size}", "最多 {size}"),
+
+ # ── 悬停提示框:鼠标停在一行上显示完整内容 ──
+ ("detailChars", "{count, plural, =1{1 character} other{{count} characters}}", "{count} 字", "{count} 文字", "{count} 字", "{count} 字"),
+ ("detailTruncated", "… {count} characters in total", "…… 共 {count} 字", "…(全 {count} 文字)", "…… 共 {count} 字", "…… 共 {count} 字"),
+ ("detailMoreFiles", "{count, plural, =1{1 more} other{{count} more}}", "还有 {count} 个", "ほか {count} 件", "還有 {count} 個", "還有 {count} 個"),
+ ("detailReceiveFirst", "Pick it to download it first", "选中后先下载", "選ぶと先にダウンロードします", "選取後先下載", "選取後先下載"),
+ ("detailTotalSize", "{size} in total", "共 {size}", "合計 {size}", "共 {size}", "共 {size}"),
+
+ # ── 快捷粘贴窗口:设置页 ──
+ ("quickPaste", "Quick paste", "快捷粘贴", "クイックペースト", "快速貼上", "快速貼上"),
+ ("quickPasteWindow", "Quick paste window", "快捷粘贴窗口", "クイックペーストウィンドウ", "快速貼上視窗", "快速貼上視窗"),
+ ("quickPasteWindowDesc", "Press the shortcut in any app to bring up your history; pick an item and it's pasted", "在任何程序里按快捷键呼出复制记录,选中即粘贴", "どのアプリでもショートカットで履歴を表示し、選ぶとペーストします", "在任何程式裡按快速鍵叫出複製記錄,選取即貼上", "在任何程式裏按快速鍵叫出複製記錄,選取即貼上"),
+ ("quickPasteShortcut", "Shortcut", "快捷键", "ショートカット", "快速鍵", "快速鍵"),
+ ("quickPasteRecord", "Click to change", "点击录制", "クリックして変更", "按一下錄製", "按一下錄製"),
+ ("quickPasteRecording", "Press the new shortcut…", "请按下新的快捷键…", "新しいショートカットを押してください…", "請按下新的快速鍵…", "請按下新的快速鍵…"),
+ ("quickPasteUseDefault", "Use default", "恢复默认", "デフォルトに戻す", "恢復預設", "恢復預設"),
+ ("quickPasteNeedsModifier", "Include ⌃, ⌥, ⇧ or ⌘, or use a function key", "要带上 ⌃、⌥、⇧ 或 ⌘,或者用功能键", "⌃、⌥、⇧、⌘ のいずれかを含めるか、ファンクションキーを使ってください", "要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵", "要加上 ⌃、⌥、⇧ 或 ⌘,或者用功能鍵"),
+ ("quickPasteNeedsModifierPc", "Include Ctrl, Alt, Shift or the Windows key, or use a function key", "要带上 Ctrl、Alt、Shift 或 Win 键,或者用功能键", "Ctrl、Alt、Shift、Windows キーのいずれかを含めるか、ファンクションキーを使ってください", "要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵", "要加上 Ctrl、Alt、Shift 或 Win 鍵,或者用功能鍵"),
+ ("quickPasteAfterPick", "After you pick an item", "选中后", "選んだ後", "選取後", "選取後"),
+ ("quickPastePasteIt", "Paste it", "直接粘贴", "ペーストする", "直接貼上", "直接貼上"),
+ ("quickPasteCopyIt", "Just copy it", "只放进剪贴板", "コピーのみ", "只放進剪貼簿", "只放入剪貼簿"),
+ ("quickPasteAccessibility", "Accessibility", "辅助功能权限", "アクセシビリティ", "輔助使用權限", "輔助使用權限"),
+ ("quickPasteAccessibilityDesc", "Needed to paste for you. Without it, items are copied and you press ⌘V.", "直接粘贴需要它;没有授权时只放进剪贴板,再由你按 ⌘V", "ペーストするのに必要です。許可しない場合はコピーだけされ、⌘V で貼り付けます。", "直接貼上需要它;沒有授權時只放進剪貼簿,再由你按 ⌘V", "直接貼上需要它;沒有授權時只放入剪貼簿,再由你按 ⌘V"),
+ ("quickPasteAllowed", "Allowed", "已授权", "許可済み", "已授權", "已授權"),
+ ("quickPasteAllow", "Allow…", "去授权", "許可する…", "去授權", "去授權"),
+ ("quickPasteNotRunning", "The quick paste window isn't running", "快捷粘贴窗口没有运行", "クイックペーストウィンドウが起動していません", "快速貼上視窗沒有在執行", "快速貼上視窗未有執行"),
+ ("quickPasteInUse", "{key} is used by another app. Pick another shortcut.", "{key} 已被其他程序占用,换一个组合", "{key} は別のアプリが使用しています。別のショートカットを選んでください。", "{key} 已被其他程式佔用,請換一個組合", "{key} 已被其他程式佔用,請換一個組合"),
+ ("quickPasteHotkeyFailed", "Couldn't set {key}: {detail}", "设置 {key} 失败:{detail}", "{key} を設定できませんでした:{detail}", "設定 {key} 失敗:{detail}", "無法設定 {key}:{detail}"),
+ ("quickPastePortalKey", "Set in the system shortcut settings", "在系统的快捷键设置里修改", "システムのショートカット設定で変更します", "在系統的快速鍵設定裡修改", "在系統的快速鍵設定裏修改"),
+ ("quickPasteWaylandDesc", "On Wayland, add the shortcut in your desktop's keyboard settings. Picked items are copied; press Ctrl+V to paste.", "Wayland 下快捷键要加在桌面的键盘设置里;选中后放进剪贴板,再按 Ctrl+V 粘贴", "Wayland ではデスクトップのキーボード設定でショートカットを追加します。選ぶとコピーされるので、Ctrl+V で貼り付けてください。", "Wayland 下快速鍵要加在桌面的鍵盤設定裡;選取後放進剪貼簿,再按 Ctrl+V 貼上", "Wayland 下快速鍵要加在桌面的鍵盤設定裏;選取後放入剪貼簿,再按 Ctrl+V 貼上"),
+ ("quickPasteAddShortcut", "Add system shortcut", "添加系统快捷键", "システムのショートカットを追加", "新增系統快速鍵", "新增系統快速鍵"),
+ ("quickPasteShortcutAdded", "Added. Press {key} to try it.", "已添加,按 {key} 试试", "追加しました。{key} を押して試してください。", "已新增,按 {key} 試試", "已新增,按 {key} 試試"),
+ ("quickPasteShortcutManual", "Add a custom shortcut in your desktop's keyboard settings that runs: {command}", "在桌面的键盘设置里添加一个自定义快捷键,命令填:{command}", "デスクトップのキーボード設定で、次のコマンドを実行するカスタムショートカットを追加してください:{command}", "在桌面的鍵盤設定裡新增一個自訂快速鍵,指令填:{command}", "在桌面的鍵盤設定裏新增一個自訂快速鍵,指令填:{command}"),
+
+ # ── 快捷粘贴窗口本身 ──
+ ("pickerSearch", "Search", "搜索", "検索", "搜尋", "搜尋"),
+ ("pickerPaste", "Paste", "粘贴", "ペースト", "貼上", "貼上"),
+ ("pickerPlainText", "Plain text", "纯文本", "プレーンテキスト", "純文字", "純文字"),
+ ("pickerCopyOnly", "Copy only", "只复制", "コピーのみ", "只複製", "只複製"),
+ ("pickerUnfavoriteHint", "Remove (back to History)", "取消收藏(放回复制记录)", "お気に入りから外す(履歴に戻す)", "取消收藏(放回複製記錄)", "取消收藏(放回複製記錄)"),
+ ("pickerPasteManually", "Picked items are copied — press {key} to paste", "选中后按 {key} 粘贴", "選ぶとコピーされます。{key} で貼り付けてください", "選取後按 {key} 貼上", "選取後按 {key} 貼上"),
+ ("pickerGrantHint", "Allow Accessibility to paste directly", "授予「辅助功能」权限后可直接粘贴", "アクセシビリティを許可すると直接ペーストできます", "授予「輔助使用」權限後可直接貼上", "授予「輔助使用」權限後可直接貼上"),
+ ("pickerDownloading", "Downloading — pastes when done", "正在下载,下完自动粘贴", "ダウンロード中。完了するとペーストします", "正在下載,下載完自動貼上", "正在下載,下載完自動貼上"),
+
# ── 图片预览 ──
("imagePreviewTitle", "Image preview", "图片预览", "画像プレビュー", "圖片預覽", "圖片預覽"),
("closePreview", "Close preview", "关闭预览", "プレビューを閉じる", "關閉預覽", "關閉預覽"),