From 8d66d45c7bfb10f1442463bf3c7f21192966fbfe Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 22:10:13 +0800 Subject: [PATCH 1/5] =?UTF-8?q?feat(app/workbench):=20=E5=9C=A8=E6=A1=8C?= =?UTF-8?q?=E9=9D=A2=E5=B7=A5=E4=BD=9C=E5=8F=B0=E9=80=89=E6=8B=A9=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=AD=97=E4=BD=93=E5=92=8C=E4=B8=AA=E4=BA=BA=E5=AD=97?= =?UTF-8?q?=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:用户需要先找到已安装字体对应的文件,「上传字体」也容易让人误解本机处理流程。 解决手段:在支持本机字体库的引擎上提供可搜索的系统和个人字体列表、目录与刷新入口。选中后沿用工作台已有的字体保存和生成流程。 收益:桌面用户可以直接使用已安装的字体,也可以批量维护个人字体;其它客户端仍可从文件导入。 --- app/README.md | 3 +- app/lib/l10n/app_en.arb | 20 +- app/lib/l10n/app_zh.arb | 14 +- .../screens/dialogs/local_font_dialog.dart | 231 ++++++++++++++++++ app/lib/screens/workbench.dart | 15 ++ app/lib/services/api.dart | 5 + app/lib/services/engine_gateway.dart | 6 +- app/lib/services/local_fonts.dart | 60 +++++ app/lib/widgets/workbench_settings.dart | 225 ++++++++--------- app/test/local_font_dialog_test.dart | 107 ++++++++ 10 files changed, 573 insertions(+), 113 deletions(-) create mode 100644 app/lib/screens/dialogs/local_font_dialog.dart create mode 100644 app/lib/services/local_fonts.dart create mode 100644 app/test/local_font_dialog_test.dart diff --git a/app/README.md b/app/README.md index 0117a945..a668e12e 100644 --- a/app/README.md +++ b/app/README.md @@ -11,7 +11,8 @@ UI 采用新艺术运动风格的 Material Design 3 主题,浅色使用暖白 - 桌面三栏工作台、手机分段工作台、中文/英文、系统主题及明暗切换。手机工具菜单显示图标、名称与用途说明,键盘展开时隐藏底部导航和导出操作。 - 长文本编辑、撤销/重做、TXT/DOCX/PDF/RTF 导入、插图及比例设置、分页和右对齐。 - Markdown 预览与清洗(四种表格格式)、LaTeX 公式预览与 Unicode 转换、常见 CircuiTikZ 电路手写绘制、中文书信排版。 -- 内置/上传字体、背景上传、背景边距识别、全部现有排版/扰动/墨色/删除线参数。 +- 工作台可选择内置字体,也可从文件导入 TTF / OTF。使用随桌面应用启动的本机引擎时,在「字体排版 → 本机字体库」可搜索系统字体。「我的字体 → 打开字体文件夹」适合一次添加多款字体,复制文件后点击刷新即可。该目录位于用户数据目录,升级应用时可保留。 +- 背景上传、背景边距识别、全部现有排版/扰动/墨色/删除线参数。 - 内置预设、自定义预设保存/加载、JSON 导入/导出、设备草稿自动保存。 - 「纸张 → 页面排版 → 排版预设」可切换标准排版与作业笔记;作业笔记增加正文留白和条目续行缩进,长公式优先在关系符处换行,保留原文、字体、背景及横线对齐。选择随草稿和参数预设保存,旧草稿默认使用标准排版。 - 预览支持缩放和翻页。开启「即时预览」后,修改文字或排版参数会自动刷新。开启「预览全部页面」可检查整份稿件,关闭时只预览第一页。可保存单页 PNG,或导出全部页面为 PDF 或图片 ZIP。生成时显示任务进度与队列状态。 diff --git a/app/lib/l10n/app_en.arb b/app/lib/l10n/app_en.arb index 9e9257eb..b63cb227 100644 --- a/app/lib/l10n/app_en.arb +++ b/app/lib/l10n/app_en.arb @@ -20,7 +20,25 @@ "redo": "Redo", "parameters": "Paper & handwriting", "font": "Handwriting font", - "uploadFont": "Upload font", + "importFontFile": "Import font from file", + "localFonts": "Local font library", + "systemFonts": "System fonts", + "personalFonts": "My fonts", + "searchFonts": "Search font names", + "openFontFolder": "Open font folder", + "refreshFonts": "Refresh font list", + "moreFonts": "Show more fonts", + "noMatchingFonts": "No matching fonts", + "personalFontsEmpty": "Add TTF or OTF files to this folder, then refresh the list.", + "openFontFolderFailed": "Open this folder manually: {path}", + "chooseBundledFont": "Choose a bundled font", + "@openFontFolderFailed": { + "placeholders": { + "path": { + "type": "String" + } + } + }, "background": "Paper background", "uploadBackground": "Upload background", "detectBackground": "Detect margins & spacing", diff --git a/app/lib/l10n/app_zh.arb b/app/lib/l10n/app_zh.arb index 6e227a3c..3899a3ee 100644 --- a/app/lib/l10n/app_zh.arb +++ b/app/lib/l10n/app_zh.arb @@ -20,7 +20,19 @@ "redo": "重做", "parameters": "纸张与笔迹", "font": "手写字体", - "uploadFont": "上传字体", + "importFontFile": "从文件导入字体", + "localFonts": "本机字体库", + "systemFonts": "系统字体", + "personalFonts": "我的字体", + "searchFonts": "搜索字体名称", + "openFontFolder": "打开字体文件夹", + "refreshFonts": "刷新字体列表", + "moreFonts": "显示更多字体", + "noMatchingFonts": "未找到匹配的字体", + "personalFontsEmpty": "将 TTF 或 OTF 字体放入此文件夹,然后刷新列表。", + "openFontFolderFailed": "请手动打开字体文件夹:{path}", + "@openFontFolderFailed": {"placeholders": {"path": {"type": "String"}}}, + "chooseBundledFont": "选择内置字体", "background": "纸张背景", "uploadBackground": "上传背景", "detectBackground": "识别边距和行距", diff --git a/app/lib/screens/dialogs/local_font_dialog.dart b/app/lib/screens/dialogs/local_font_dialog.dart new file mode 100644 index 00000000..4cae770c --- /dev/null +++ b/app/lib/screens/dialogs/local_font_dialog.dart @@ -0,0 +1,231 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../services/api.dart'; +import '../../services/local_fonts.dart'; + +class LocalFontDialog extends StatefulWidget { + const LocalFontDialog({super.key, required this.api}); + final HandwritingApi api; + + @override + State createState() => _LocalFontDialogState(); +} + +class _LocalFontDialogState extends State { + final search = TextEditingController(); + final scroll = ScrollController(); + LocalFontSource source = LocalFontSource.system; + List fonts = []; + String? directory; + int? nextOffset; + int generation = 0; + bool loading = true; + Object? error; + Timer? debounce; + + @override + void initState() { + super.initState(); + load(); + } + + @override + void dispose() { + debounce?.cancel(); + search.dispose(); + scroll.dispose(); + super.dispose(); + } + + void reload({bool typing = false, bool refresh = false}) { + debounce?.cancel(); + generation++; + if (scroll.hasClients) scroll.jumpTo(0); + setState(() { + fonts = []; + nextOffset = null; + error = null; + loading = true; + }); + if (typing) { + debounce = Timer(const Duration(milliseconds: 200), load); + } else { + load(refresh: refresh); + } + } + + Future load({bool refresh = false}) async { + final request = ++generation; + setState(() { + loading = true; + error = null; + }); + try { + final page = await widget.api.listLocalFonts( + source: source, + query: search.text.trim(), + offset: nextOffset ?? 0, + refresh: refresh, + ); + if (!mounted || request != generation) return; + setState(() { + fonts = [...fonts, ...page.fonts]; + nextOffset = page.nextOffset; + directory = page.directory; + loading = false; + }); + } catch (e) { + if (!mounted || request != generation) return; + setState(() { + error = e; + loading = false; + }); + } + } + + Future openDirectory() async { + final path = directory; + if (path == null) return; + try { + if (await launchUrl( + Uri.directory(path), + mode: LaunchMode.externalApplication, + )) { + return; + } + } catch (_) { + // Show the path so it can still be opened manually. + } + if (mounted) { + final l = AppLocalizations.of(context)!; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: SelectableText(l.openFontFolderFailed(path))), + ); + } + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + final personal = source == LocalFontSource.user; + return AlertDialog( + title: Text(l.localFonts), + content: SizedBox( + width: 460, + height: 420, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SegmentedButton( + segments: [ + ButtonSegment( + value: LocalFontSource.system, + label: Text(l.systemFonts), + ), + ButtonSegment( + value: LocalFontSource.user, + label: Text(l.personalFonts), + ), + ], + selected: {source}, + onSelectionChanged: (selection) { + source = selection.single; + search.clear(); + reload(); + }, + ), + const SizedBox(height: 12), + TextField( + controller: search, + onChanged: (_) => reload(typing: true), + decoration: InputDecoration( + prefixIcon: const Icon(Icons.search), + hintText: l.searchFonts, + ), + ), + if (personal) + Row( + children: [ + Expanded( + child: Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton.icon( + onPressed: directory == null ? null : openDirectory, + icon: const Icon(Icons.folder_open_outlined), + label: Text(l.openFontFolder), + ), + ), + ), + IconButton( + tooltip: l.refreshFonts, + onPressed: loading ? null : () => reload(refresh: true), + icon: const Icon(Icons.refresh), + ), + ], + ), + const SizedBox(height: 6), + Expanded( + child: ListView.builder( + controller: scroll, + itemCount: fonts.length + 1, + itemBuilder: (context, index) { + if (index < fonts.length) { + final font = fonts[index]; + return ListTile( + title: Text(font.name), + subtitle: font.filename == font.name + ? null + : Text( + font.filename, + overflow: TextOverflow.ellipsis, + ), + onTap: () => Navigator.pop(context, font), + ); + } + if (loading) { + return const Center(child: CircularProgressIndicator()); + } + if (error != null) { + return Column( + children: [ + SelectableText('${l.errorTitle}: $error'), + TextButton(onPressed: load, child: Text(l.retry)), + ], + ); + } + if (nextOffset != null) { + return TextButton( + onPressed: load, + child: Text(l.moreFonts), + ); + } + if (fonts.isEmpty) { + return Padding( + padding: const EdgeInsets.all(12), + child: Text( + personal && search.text.trim().isEmpty + ? l.personalFontsEmpty + : l.noMatchingFonts, + ), + ); + } + return const SizedBox.shrink(); + }, + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + ], + ); + } +} diff --git a/app/lib/screens/workbench.dart b/app/lib/screens/workbench.dart index 168acba1..e099a720 100644 --- a/app/lib/screens/workbench.dart +++ b/app/lib/screens/workbench.dart @@ -11,6 +11,8 @@ import '../l10n/app_localizations.dart'; import '../models/engine_failure.dart'; import 'dialogs/connection_dialog.dart'; import 'dialogs/illustration_dialog.dart'; +import 'dialogs/local_font_dialog.dart'; +import '../services/local_fonts.dart'; import 'dialogs/paper_area_dialog.dart'; import '../utils/image_data.dart'; import '../utils/image_markers.dart'; @@ -764,6 +766,19 @@ class _WorkbenchState extends State with WidgetsBindingObserver { color: value.toARGB32(), )); }, + onBrowseLocalFonts: w.managedBackend && w.api.supportsLocalFonts + ? () => action(() async { + final font = await showDialog( + context: context, + builder: (_) => LocalFontDialog(api: w.api), + ); + if (font == null || !mounted) return; + final file = await w.api.readLocalFont(font); + if (!mounted) return; + w.fontFile = file; + w.edit(); + }) + : null, onUploadFont: () => action(() async { final file = await pick(['ttf', 'otf']); if (file != null) { diff --git a/app/lib/services/api.dart b/app/lib/services/api.dart index 0bf157f5..4d84db36 100644 --- a/app/lib/services/api.dart +++ b/app/lib/services/api.dart @@ -137,8 +137,13 @@ class HandwritingApi { } bool get supportsCancel => _supportsCancel; + bool supportsLocalFonts = false; bool supportsFineEdit = false; void configureCapabilities(dynamic info) { + supportsLocalFonts = + info is Map && + info['capabilities'] is Map && + info['capabilities']['local_fonts'] == true; supportsFineEdit = info is Map && info['capabilities'] is Map && diff --git a/app/lib/services/engine_gateway.dart b/app/lib/services/engine_gateway.dart index a4e8241f..b764189d 100644 --- a/app/lib/services/engine_gateway.dart +++ b/app/lib/services/engine_gateway.dart @@ -71,10 +71,11 @@ class EngineInfo { required this.canCancel, required this.canChooseTaskId, this.canFineEdit = false, + this.canListLocalFonts = false, }); final String version; final bool canCancel, canChooseTaskId; - final bool canFineEdit; + final bool canFineEdit, canListLocalFonts; factory EngineInfo.fromJson(Map value) { final capabilities = value['capabilities']; return EngineInfo( @@ -83,6 +84,8 @@ class EngineInfo { capabilities is Map && capabilities['task_cancellation'] == true, canChooseTaskId: capabilities is Map && capabilities['task_submission_id'] == true, + canListLocalFonts: + capabilities is Map && capabilities['local_fonts'] == true, canFineEdit: capabilities is Map && capabilities['fine_edit'] == true, ); } @@ -126,6 +129,7 @@ class ApiEngineGateway implements EngineGateway, EngineCatalog { 'task_cancellation': info.canCancel, 'task_submission_id': info.canChooseTaskId, 'fine_edit': info.canFineEdit, + 'local_fonts': info.canListLocalFonts, }, }); diff --git a/app/lib/services/local_fonts.dart b/app/lib/services/local_fonts.dart new file mode 100644 index 00000000..bca08371 --- /dev/null +++ b/app/lib/services/local_fonts.dart @@ -0,0 +1,60 @@ +import 'dart:convert'; + +import 'api.dart'; + +enum LocalFontSource { system, user } + +typedef LocalFont = ({String id, String name, String filename}); + +typedef LocalFontPage = ({ + List fonts, + int? nextOffset, + String directory, +}); + +extension LocalFonts on HandwritingApi { + Future listLocalFonts({ + required LocalFontSource source, + required String query, + int offset = 0, + bool refresh = false, + }) async { + final response = await checked( + client.post( + uri('/api/local_fonts'), + headers: {...headers, 'Content-Type': 'application/json'}, + body: jsonEncode({ + 'source': source.name, + 'query': query, + 'offset': offset, + 'limit': 30, + 'refresh': refresh, + }), + ), + ); + final data = jsonDecode(utf8.decode(response.bodyBytes)) as Map; + return ( + fonts: [ + for (final row in data['fonts'] as List) + ( + id: row['id'] as String, + name: row['name'] as String, + filename: row['filename'] as String, + ), + ], + nextOffset: data['next_offset'] as int?, + directory: data['user_dir'] as String, + ); + } + + Future readLocalFont(LocalFont font) async { + final response = await checked( + client.post( + uri('/api/local_fonts/read'), + headers: {...headers, 'Content-Type': 'application/json'}, + body: jsonEncode({'id': font.id}), + ), + ); + return Upload(font.filename, response.bodyBytes); + } +} diff --git a/app/lib/widgets/workbench_settings.dart b/app/lib/widgets/workbench_settings.dart index 75f79ecd..82efdca7 100644 --- a/app/lib/widgets/workbench_settings.dart +++ b/app/lib/widgets/workbench_settings.dart @@ -44,6 +44,7 @@ class WorkbenchSettings extends StatelessWidget { required this.onSelectFont, required this.onColorSelected, required this.onUploadFont, + this.onBrowseLocalFonts, required this.onRemoveFont, required this.onDefaultPreset, required this.onSmallPreset, @@ -78,7 +79,7 @@ class WorkbenchSettings extends StatelessWidget { onRemoveBackground; final ValueChanged onSelectFont; final ValueChanged onColorSelected; - final VoidCallback? onAdjustBackground; + final VoidCallback? onAdjustBackground, onBrowseLocalFonts; final SettingsSection? activeSection; final ValueChanged? onSectionChanged; final Widget? inkControls; @@ -166,117 +167,124 @@ class WorkbenchSettings extends StatelessWidget { key: PageStorageKey(activeSection), children: [ if (show(SettingsSection.layout)) ...[ - section( - 'font', - l.fontChoices, - Icons.font_download_outlined, - [ - Semantics( - identifier: 'font-select', - child: SettingsFieldLabel( - label: l.font, - child: DropdownButtonFormField( - key: ValueKey( - 'font-${settings.font}-${fontFile?.name}', - ), - initialValue: fonts.contains(settings.font) - ? settings.font - : null, - isExpanded: true, - items: fonts - .map( - (f) => DropdownMenuItem( - value: f, - child: Text( - f, - overflow: TextOverflow.ellipsis, - ), - ), - ) - .toList(), - onChanged: locked - ? null - : (value) { - onSelectFont(value); - }, - ), - ), - ), - const SizedBox(height: 6), - FilledButton.tonalIcon( - onPressed: locked ? null : onUploadFont, - icon: const Icon(Icons.upload), - label: Text( - fontFile?.name ?? l.uploadFont, - overflow: TextOverflow.ellipsis, - ), - ), - if (fontFile != null) - TextButton( - onPressed: locked ? null : onRemoveFont, - child: Text(l.remove), - ), - const SizedBox(height: 10), - SettingsFieldLabel( - label: l.latinFont, + section('font', l.fontChoices, Icons.font_download_outlined, [ + Semantics( + identifier: 'font-select', + child: SettingsFieldLabel( + label: l.font, child: DropdownButtonFormField( - key: ValueKey('latin-font-$settingsRevision'), + key: ValueKey( + 'font-${settings.font}-${fontFile?.name}', + ), + hint: Text(l.chooseBundledFont), + initialValue: + fontFile == null && fonts.contains(settings.font) + ? settings.font + : null, isExpanded: true, - initialValue: settings.latinFont ?? '', - items: [ - DropdownMenuItem( - value: '', - child: Text(l.inheritLatinFont), - ), - for (final entry in latinFonts.entries) - DropdownMenuItem( - value: entry.key, - child: Text( - entry.value, - overflow: TextOverflow.ellipsis, + items: fonts + .map( + (f) => DropdownMenuItem( + value: f, + child: Text( + f, + overflow: TextOverflow.ellipsis, + ), ), - ), - ], + ) + .toList(), onChanged: locked ? null : (value) { - settings.latinFont = value == '' - ? null - : value; - onEdited(); + onSelectFont(value); }, ), ), - NumericSlider( - label: l.latinFontScale, - id: 'latin-font-scale', - value: settings.latinScale.toDouble(), - parameter: latinScaleParameter, - unit: '%', + ), + const SizedBox(height: 6), + if (fontFile != null) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + leading: const Icon(Icons.font_download_outlined), + title: Text( + fontFile!.name, + overflow: TextOverflow.ellipsis, + ), + trailing: IconButton( + tooltip: l.remove, + onPressed: locked ? null : onRemoveFont, + icon: const Icon(Icons.close), + ), + ), + if (onBrowseLocalFonts != null) + FilledButton.tonalIcon( + onPressed: locked ? null : onBrowseLocalFonts, + icon: const Icon(Icons.font_download_outlined), + label: Text(l.localFonts), + ), + OutlinedButton.icon( + onPressed: locked ? null : onUploadFont, + icon: const Icon(Icons.file_open_outlined), + label: Text(l.importFontFile), + ), + const SizedBox(height: 10), + SettingsFieldLabel( + label: l.latinFont, + child: DropdownButtonFormField( + key: ValueKey('latin-font-$settingsRevision'), + isExpanded: true, + initialValue: settings.latinFont ?? '', + items: [ + DropdownMenuItem( + value: '', + child: Text(l.inheritLatinFont), + ), + for (final entry in latinFonts.entries) + DropdownMenuItem( + value: entry.key, + child: Text( + entry.value, + overflow: TextOverflow.ellipsis, + ), + ), + ], onChanged: locked ? null : (value) { - settings.latinScale = value.round(); + settings.latinFont = value == '' ? null : value; onEdited(); }, ), - settingSwitch( - l.digitsLatin, - settings.latinDigits, - (value) => settings.latinDigits = value, - ), - if (activeSection == null) - Align( - alignment: AlignmentDirectional.centerStart, - child: InkColorControl( - key: const ValueKey('settings-ink-color'), - color: Color(settings.inkLook.color), - onChanged: locked ? null : onColorSelected, - ), + ), + NumericSlider( + label: l.latinFontScale, + id: 'latin-font-scale', + value: settings.latinScale.toDouble(), + parameter: latinScaleParameter, + unit: '%', + onChanged: locked + ? null + : (value) { + settings.latinScale = value.round(); + onEdited(); + }, + ), + settingSwitch( + l.digitsLatin, + settings.latinDigits, + (value) => settings.latinDigits = value, + ), + if (activeSection == null) + Align( + alignment: AlignmentDirectional.centerStart, + child: InkColorControl( + key: const ValueKey('settings-ink-color'), + color: Color(settings.inkLook.color), + onChanged: locked ? null : onColorSelected, ), - ], - collapsible: false, - ), + ), + ], collapsible: false), section('layout', l.layoutPreset, Icons.space_bar, [ LayoutBuilder( builder: (context, constraints) => @@ -527,19 +535,18 @@ class WorkbenchSettings extends StatelessWidget { bool value, ValueChanged change, { IconData? icon, - }) => - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: Text(title), - secondary: icon == null ? null : Icon(icon), - value: value, - onChanged: locked - ? null - : (next) { - change(next); - onEdited(); - }, - ); + }) => SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(title), + secondary: icon == null ? null : Icon(icon), + value: value, + onChanged: locked + ? null + : (next) { + change(next); + onEdited(); + }, + ); Widget parameterGrid( BuildContext context, diff --git a/app/test/local_font_dialog_test.dart b/app/test/local_font_dialog_test.dart new file mode 100644 index 00000000..a3316ef2 --- /dev/null +++ b/app/test/local_font_dialog_test.dart @@ -0,0 +1,107 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/l10n/app_localizations.dart'; +import 'package:handwriting_app/screens/dialogs/local_font_dialog.dart'; +import 'package:handwriting_app/services/api.dart'; +import 'package:handwriting_app/services/engine_gateway.dart'; +import 'package:handwriting_app/services/local_fonts.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; + +void main() { + test( + 'only engines advertising the local font library enable it on connect', + () async { + for (final supported in [true, false]) { + final api = HandwritingApi( + 'http://localhost', + client: MockClient( + (_) async => http.Response( + jsonEncode({ + 'capabilities': {if (supported) 'local_fonts': true}, + }), + 200, + ), + ), + ); + final gateway = ApiEngineGateway(api); + gateway.configure(await gateway.loadInfo()); + expect(api.supportsLocalFonts, supported); + } + }, + ); + testWidgets( + 'changing libraries discards outstanding searches and reads the selected font by ID', + (tester) async { + final pending = Completer(); + final queries = >[]; + http.Response page(String name) => http.Response.bytes( + utf8.encode( + jsonEncode({ + 'fonts': [ + {'id': 'local-123', 'name': name, 'filename': '本机.ttf'}, + ], + 'next_offset': null, + 'user_dir': 'some-directory', + }), + ), + 200, + ); + final api = HandwritingApi( + 'http://localhost', + accessToken: 'session', + client: MockClient((req) async { + expect(req.headers['Authorization'], 'Bearer session'); + final data = jsonDecode(req.body) as Map; + if (req.url.path.endsWith('/read')) { + expect(data, {'id': 'local-123'}); + return http.Response.bytes([1, 2, 3], 200); + } + queries.add(data); + return data['source'] == 'system' ? pending.future : page('手写'); + }), + ); + Upload? chosen; + await tester.pumpWidget( + MaterialApp( + locale: const Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: ElevatedButton( + child: const Text('Pick'), + onPressed: () async { + final font = await showDialog( + context: context, + builder: (_) => LocalFontDialog(api: api), + ); + if (font != null) chosen = await api.readLocalFont(font); + }, + ), + ), + ), + ), + ); + await tester.tap(find.text('Pick')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + await tester.tap(find.text('My fonts')); + await tester.pumpAndSettle(); + pending.complete(page('Stale result')); + await tester.pumpAndSettle(); + expect(find.text('Stale result'), findsNothing); + await tester.enterText(find.byType(TextField), '手'); + await tester.pump(const Duration(milliseconds: 210)); + await tester.pumpAndSettle(); + expect(queries.last['query'], '手'); + await tester.tap(find.text('手写')); + await tester.pumpAndSettle(); + expect(chosen?.name, '本机.ttf'); + expect(chosen?.bytes, [1, 2, 3]); + }, + ); +} From a0caf94afe2e4c1bab9baf5832e51cd6b315a21d Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 22:17:57 +0800 Subject: [PATCH 2/5] =?UTF-8?q?feat(crates):=20=E8=AE=A9=E6=A1=8C=E9=9D=A2?= =?UTF-8?q?=E5=BC=95=E6=93=8E=E5=92=8C=20MCP=20=E5=85=B1=E4=BA=AB=E5=8F=AF?= =?UTF-8?q?=E6=A3=80=E7=B4=A2=E7=9A=84=E6=9C=AC=E6=9C=BA=E5=AD=97=E4=BD=93?= =?UTF-8?q?=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:内置字体可以直接按名使用,但本机安装的字和用户收集的字需要自行定位到文件。 解决手段:共用一个按名称、来源检索的目录,按字面读取 TTC 和 OTF 等资源。桌面接口仅向带令牌的本地配套引擎开放,MCP 把选中的字面随稿保存。 收益:人和代理能找到同一款字体;移动或清理原字体文件后仍能重现已有稿件。 --- Cargo.lock | 97 +++++ crates/handwriting-core/Cargo.toml | 6 + crates/handwriting-core/src/lib.rs | 2 + crates/handwriting-core/src/local_fonts.rs | 339 ++++++++++++++++++ .../handwriting-core/src/local_fonts/tests.rs | 102 ++++++ crates/handwriting-server/Cargo.toml | 2 +- crates/handwriting-server/src/lib.rs | 83 ++++- crates/handwriting-server/src/main.rs | 8 +- crates/panache-mcp/Cargo.toml | 2 +- crates/panache-mcp/README.md | 6 +- crates/panache-mcp/src/drafts.rs | 7 + crates/panache-mcp/src/inputs.rs | 2 +- crates/panache-mcp/src/main.rs | 95 +++-- crates/panache-mcp/src/tuning.rs | 41 ++- crates/panache-mcp/tests/smoke.py | 23 +- 15 files changed, 759 insertions(+), 56 deletions(-) create mode 100644 crates/handwriting-core/src/local_fonts.rs create mode 100644 crates/handwriting-core/src/local_fonts/tests.rs diff --git a/Cargo.lock b/Cargo.lock index 30da34f2..91d5a1c6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -182,6 +182,20 @@ name = "bytemuck" version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.8", +] [[package]] name = "byteorder-lite" @@ -553,6 +567,37 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontconfig-parser" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc773e24e02d4ddd8395fd30dc147524273a83e54e0f312d986ea30de5f5646" +dependencies = [ + "roxmltree", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "fontconfig-parser", + "log", + "memmap2", + "slotmap", + "tinyvec", +] + [[package]] name = "fontdue" version = "0.9.4" @@ -770,6 +815,7 @@ version = "0.1.0" dependencies = [ "base64 0.23.1", "flate2", + "fontdb", "fontdue", "icu_properties", "image", @@ -781,12 +827,14 @@ dependencies = [ "rand 0.10.3", "rand_chacha 0.10.0", "rand_distr", + "schemars", "serde", "serde_json", "sha2 0.10.9", "tempfile", "thiserror", "ttf-parser", + "write-fonts", "zip", ] @@ -1291,6 +1339,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + [[package]] name = "mime" version = "0.3.17" @@ -1752,6 +1809,20 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" +[[package]] +name = "read-fonts" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a39d2f8f681030a7bcbbcf3e8568775ac2393afd51401a2e2133ee89e3953897" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types", + "once_cell", + "smallvec", + "yoke", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -1822,6 +1893,12 @@ dependencies = [ "syn 3.0.8", ] +[[package]] +name = "roxmltree" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" + [[package]] name = "rquickjs" version = "0.14.0" @@ -2107,6 +2184,15 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + [[package]] name = "smallvec" version = "1.16.3" @@ -2817,6 +2903,17 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "write-fonts" +version = "0.56.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "944049531d52f9002812ea9de23ec8aa4e9577a7bee6869a1d0f297c679817ea" +dependencies = [ + "font-types", + "log", + "read-fonts", +] + [[package]] name = "writeable" version = "0.6.4" diff --git a/crates/handwriting-core/Cargo.toml b/crates/handwriting-core/Cargo.toml index b154941f..966e8132 100644 --- a/crates/handwriting-core/Cargo.toml +++ b/crates/handwriting-core/Cargo.toml @@ -5,7 +5,13 @@ edition.workspace = true publish.workspace = true license.workspace = true +[features] +local-fonts = ["dep:fontdb", "dep:schemars", "dep:write-fonts"] + [dependencies] +schemars = { version = "1", optional = true } +fontdb = { version = "0.24", optional = true } +write-fonts = { version = "0.56", default-features = false, features = ["read"], optional = true } base64 = "0.23.1" flate2 = "1.1.10" fontdue = "0.9.4" diff --git a/crates/handwriting-core/src/lib.rs b/crates/handwriting-core/src/lib.rs index 65955adc..df3b875c 100644 --- a/crates/handwriting-core/src/lib.rs +++ b/crates/handwriting-core/src/lib.rs @@ -7,6 +7,8 @@ pub mod generation; pub mod imaging; pub mod ink_effects; mod inline_document; +#[cfg(feature = "local-fonts")] +pub mod local_fonts; pub use inline_document::{review_text, validate as validate_document}; mod parameters; pub mod photo; diff --git a/crates/handwriting-core/src/local_fonts.rs b/crates/handwriting-core/src/local_fonts.rs new file mode 100644 index 00000000..8693c26b --- /dev/null +++ b/crates/handwriting-core/src/local_fonts.rs @@ -0,0 +1,339 @@ +//! Searchable on-device font catalog shared by the desktop sidecar and the stdio MCP server. +use crate::{Error, FontBook, Result}; +use fontdb::{Database, Source}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::HashSet, + env, fs, + path::{Path, PathBuf}, + sync::Mutex, +}; +use write_fonts::{FontBuilder, read::FontRef, types::Tag}; + +#[derive( + Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, JsonSchema, +)] +#[serde(rename_all = "snake_case")] +pub enum FontSource { + Bundled, + User, + System, +} + +#[derive(Clone, Serialize)] +pub struct FontEntry { + pub id: String, + pub name: String, + pub filename: String, + pub source: FontSource, +} + +#[derive(Default, Deserialize, JsonSchema)] +#[serde(default, deny_unknown_fields)] +pub struct FontSearch { + /// Case-insensitive substring of the face, localized family or filename. + pub query: String, + pub source: Option, + pub offset: usize, + /// Number of faces to return (default 20, maximum 100). + pub limit: Option, + /// Rescan after adding, removing or installing fonts. + pub refresh: bool, +} + +#[derive(Serialize)] +pub struct FontPage { + pub fonts: Vec, + pub total: usize, + pub next_offset: Option, + pub user_dir: PathBuf, +} + +struct Entry { + info: FontEntry, + keywords: String, + face: Option, +} + +struct Index { + db: Database, + entries: Vec, +} + +pub struct LocalFonts { + bundled: Vec, + user_dir: Option, + max_bytes: usize, + index: Mutex>, +} + +fn user_dir() -> Option { + if let Some(path) = env::var_os("PANACHE_USER_FONT_DIR") { + return Some(path.into()); + } + let base = if cfg!(windows) { + env::var_os("LOCALAPPDATA").map(PathBuf::from) + } else if cfg!(target_os = "macos") { + env::var_os("HOME").map(|v| PathBuf::from(v).join("Library/Application Support")) + } else { + env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .or_else(|| env::var_os("HOME").map(|v| PathBuf::from(v).join(".local/share"))) + }; + base.map(|base| base.join("Panache/fonts")) +} + +fn invalid(message: impl Into) -> Error { + Error::new("invalid_font", message) +} + +// The render and workspace formats both expect face zero in one standalone font. +// Size the actual selected face before allocating, even for a very large CJK collection. +fn face_format(data: &[u8], index: u32, limit: usize) -> Option<(&'static str, bool)> { + let font = FontRef::from_index(data, index).ok()?; + let records = font.table_directory().table_records(); + let has = |tag: &[u8; 4]| records.iter().any(|r| r.tag() == Tag::new(tag)); + let ext = if has(b"glyf") { + "ttf" + } else if has(b"CFF ") || has(b"CFF2") { + "otf" + } else { + return None; + }; + let collection = data.starts_with(b"ttcf"); + let size = if collection { + records.iter().try_fold(12 + 16 * records.len(), |n, r| { + n.checked_add((r.length() as usize).checked_add(3)? & !3) + })? + } else { + data.len() + }; + (size <= limit).then_some((ext, collection)) +} + +fn display_name(data: &[u8], idx: u32) -> Option { + let face = ttf_parser::RawFace::parse(data, idx).ok()?; + let names = + ttf_parser::name::Table::parse(face.table(ttf_parser::Tag::from_bytes(b"name"))?)?.names; + let mut english = None; + let mut chinese = None; + let mut first = None; + for name in names + .into_iter() + .filter(|n| n.name_id == ttf_parser::name_id::FULL_NAME) + { + let Some(text) = name.to_string().filter(|s| !s.trim().is_empty()) else { + continue; + }; + match name.language() { + ttf_parser::Language::Chinese_PeoplesRepublicOfChina => chinese = Some(text), + ttf_parser::Language::English_UnitedStates => english = Some(text), + _ => { + first.get_or_insert(text); + } + } + } + match (chinese, english) { + (Some(zh), Some(en)) if en != zh => Some(format!("{zh} ({en})")), + (zh, en) => zh.or(en).or(first), + } +} + +impl LocalFonts { + pub fn new(bundled: Vec, max_bytes: usize) -> Self { + Self { + bundled, + user_dir: user_dir(), + max_bytes, + index: Mutex::new(None), + } + } + + fn scan(&self, user_dir: &Path, system: impl FnOnce(&mut Database)) -> Result { + if !user_dir.is_absolute() { + return Err(invalid( + "PANACHE_USER_FONT_DIR must be an absolute directory", + )); + } + fs::create_dir_all(user_dir).map_err(|e| invalid(e.to_string()))?; + let mut db = Database::new(); + db.load_fonts_dir(user_dir); + let user_ids: HashSet<_> = db.faces().map(|f| f.id).collect(); + system(&mut db); + let mut entries = self + .bundled + .iter() + .map(|name| Entry { + info: FontEntry { + id: name.clone(), + name: name.clone(), + filename: name.clone(), + source: FontSource::Bundled, + }, + keywords: name.to_lowercase(), + face: None, + }) + .collect::>(); + let mut seen = HashSet::new(); + for face in db.faces() { + let Source::File(path) = &face.source else { + continue; + }; + let Some(((ext, collection), title)) = db + .with_face_data(face.id, |data, idx| { + Some(( + face_format(data, idx, self.max_bytes)?, + display_name(data, idx), + )) + }) + .flatten() + else { + continue; + }; + if !seen.insert((path, face.index)) { + continue; + } + let user = user_ids.contains(&face.id); + let source = if user { + FontSource::User + } else { + FontSource::System + }; + let prefix = if user { "user" } else { "system" }; + let hash = Sha256::new() + .chain_update(path.as_os_str().as_encoded_bytes()) + .chain_update(face.index.to_be_bytes()) + .finalize(); + let digest = format!("{hash:x}"); + let id = format!("{prefix}:{}", &digest[..24]); + let basename = path.file_name().unwrap_or_default().to_string_lossy(); + let family = face + .families + .iter() + .map(|(name, _)| name.as_str()) + .collect::>() + .join(" "); + let name = title.unwrap_or_else(|| face.post_script_name.clone()); + let filename = if collection { + format!( + "{}-{}.{}", + path.file_stem().unwrap_or_default().to_string_lossy(), + face.index + 1, + ext + ) + } else { + basename.to_string() + }; + entries.push(Entry { + keywords: format!( + "{name} {family} {basename} {filename} {}", + face.post_script_name + ) + .to_lowercase(), + info: FontEntry { + id, + name, + filename, + source, + }, + face: Some(face.id), + }); + } + entries.sort_by(|a, b| { + (a.info.source, &a.info.name, &a.info.id).cmp(&( + b.info.source, + &b.info.name, + &b.info.id, + )) + }); + Ok(Index { db, entries }) + } + + fn with_index( + &self, + refresh: bool, + visit: impl FnOnce(&Index, &Path) -> Result, + ) -> Result { + let dir = self + .user_dir + .as_deref() + .ok_or_else(|| invalid("Set PANACHE_USER_FONT_DIR to a writable directory"))?; + let mut cache = self + .index + .lock() + .map_err(|_| invalid("Font catalog unavailable"))?; + if cache.is_none() || refresh { + *cache = Some(self.scan(dir, Database::load_system_fonts)?); + } + visit(cache.as_ref().unwrap(), dir) + } + + pub fn search(&self, search: &FontSearch) -> Result { + let limit = search.limit.unwrap_or(20); + if !(1..=100).contains(&limit) { + return Err(invalid("Font search limit must be 1..100")); + } + let keyword = search.query.trim().to_lowercase(); + self.with_index(search.refresh, |index, dir| { + let mut fonts = Vec::new(); + let mut total = 0; + for entry in &index.entries { + if search.source.is_some_and(|s| s != entry.info.source) + || !entry.keywords.contains(&keyword) + { + continue; + } + if total >= search.offset && fonts.len() < limit { + fonts.push(entry.info.clone()); + } + total += 1; + } + let end = search.offset.saturating_add(fonts.len()); + Ok(FontPage { + fonts, + total, + next_offset: (end < total).then_some(end), + user_dir: dir.into(), + }) + }) + } + + pub fn read(&self, id: &str) -> Result<(FontEntry, Vec)> { + self.with_index(false, |index, _| { + let entry = index + .entries + .iter() + .find(|e| e.info.id == id) + .ok_or_else(|| invalid("Unknown local font ID. Search or refresh the catalog."))?; + let face = entry + .face + .ok_or_else(|| invalid("Choose a user or system font ID"))?; + let bytes = index + .db + .with_face_data(face, |data, idx| { + let (_, collection) = face_format(data, idx, self.max_bytes)?; + if collection { + Some( + FontBuilder::new() + .copy_missing_tables(FontRef::from_index(data, idx).ok()?) + .build(), + ) + } else { + Some(data.to_vec()) + } + }) + .flatten() + .ok_or_else(|| invalid("Font is unavailable or exceeds the upload limit"))?; + if bytes.len() > self.max_bytes { + return Err(invalid("Font exceeds the upload limit")); + } + FontBook::load(&bytes)?; + Ok((entry.info.clone(), bytes)) + }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/handwriting-core/src/local_fonts/tests.rs b/crates/handwriting-core/src/local_fonts/tests.rs new file mode 100644 index 00000000..bfdef0fb --- /dev/null +++ b/crates/handwriting-core/src/local_fonts/tests.rs @@ -0,0 +1,102 @@ +use super::*; +use tempfile::tempdir; + +const HANDLEE: &[u8] = include_bytes!("../../assets/latin/Handlee-Regular.ttf"); +const INDIE: &[u8] = include_bytes!("../../assets/latin/IndieFlower-Regular.ttf"); + +// Two genuinely different faces. TTC table offsets are relative to the entire collection. +fn collection() -> Vec { + let mut out = b"ttcf\0\x01\0\0\0\0\0\x02".to_vec(); + out.resize(20, 0); + for (idx, font) in [HANDLEE, INDIE].into_iter().enumerate() { + let start = out.len(); + out[12 + 4 * idx..16 + 4 * idx].copy_from_slice(&(start as u32).to_be_bytes()); + out.extend_from_slice(font); + let tables = u16::from_be_bytes([font[4], font[5]]) as usize; + for i in 0..tables { + let field = &mut out[start + 20 + 16 * i..start + 24 + 16 * i]; + let offset = u32::from_be_bytes(field.try_into().unwrap()) + start as u32; + field.copy_from_slice(&offset.to_be_bytes()); + } + out.resize(out.len().next_multiple_of(4), 0); + } + out +} + +#[test] +fn search_pages_sources_and_collection_face_bytes() { + let home = tempdir().unwrap(); + let user = home.path().join("my-fonts"); + let system = home.path().join("system"); + fs::create_dir_all(&system).unwrap(); + fs::create_dir_all(&user).unwrap(); + fs::write(system.join("sample.ttf"), HANDLEE).unwrap(); + fs::write(user.join("sample.ttf"), INDIE).unwrap(); + fs::write(user.join("collection.ttc"), collection()).unwrap(); + fs::write(user.join("bad.ttf"), b"not a font").unwrap(); + let catalog = LocalFonts { + user_dir: Some(user.clone()), + ..LocalFonts::new(vec!["sample.ttf".to_owned()], 110_000) + }; + let index = catalog + .scan(&user, |db| db.load_fonts_dir(&system)) + .unwrap(); + *catalog.index.lock().unwrap() = Some(index); + + let first = catalog + .search(&FontSearch { + limit: Some(2), + ..Default::default() + }) + .unwrap(); + assert_eq!((first.total, first.next_offset), (5, Some(2))); + assert_eq!(first.fonts[0].id, "sample.ttf"); + let last = catalog + .search(&FontSearch { + offset: 2, + ..Default::default() + }) + .unwrap(); + assert_eq!((last.fonts.len(), last.next_offset), (3, None)); + let query = |q: &str, source| { + catalog + .search(&FontSearch { + query: q.into(), + source: Some(source), + ..Default::default() + }) + .unwrap() + .fonts + }; + let twins = query("SAMPLE", FontSource::System); + assert_eq!(twins.len(), 1); + let personal = query("sample", FontSource::User); + assert_ne!(personal[0].id, twins[0].id); + assert_eq!(catalog.read(&personal[0].id).unwrap().1, INDIE); + assert!(catalog.read("../sample.ttf").is_err()); + assert!(catalog.read("sample.ttf").is_err()); + let faces = query("COLLECTION", FontSource::User); + assert_eq!(faces.len(), 2); + for face in faces { + assert!(face.filename.ends_with(".ttf")); + let bytes = catalog.read(&face.id).unwrap().1; + assert!(!bytes.starts_with(b"ttcf")); + assert_eq!(display_name(&bytes, 0).as_ref(), Some(&face.name)); + let expected = if face.filename.ends_with("-2.ttf") { + INDIE + } else { + HANDLEE + }; + assert_eq!(display_name(expected, 0), display_name(&bytes, 0)); + } + assert!( + catalog + .search(&FontSearch { + limit: Some(101), + ..Default::default() + }) + .is_err() + ); + fs::remove_file(user.join("sample.ttf")).unwrap(); + assert!(catalog.read(&personal[0].id).is_err()); +} diff --git a/crates/handwriting-server/Cargo.toml b/crates/handwriting-server/Cargo.toml index 27a16d5b..1eccc65c 100644 --- a/crates/handwriting-server/Cargo.toml +++ b/crates/handwriting-server/Cargo.toml @@ -6,7 +6,7 @@ publish.workspace = true license.workspace = true [dependencies] -handwriting-core.workspace = true +handwriting-core = { workspace = true, features = ["local-fonts"] } axum = { workspace = true, features = ["multipart", "ws"] } serde.workspace = true tokio = { workspace = true, features = ["fs", "sync", "time"] } diff --git a/crates/handwriting-server/src/lib.rs b/crates/handwriting-server/src/lib.rs index 667fe9a9..5083dbb6 100644 --- a/crates/handwriting-server/src/lib.rs +++ b/crates/handwriting-server/src/lib.rs @@ -20,6 +20,7 @@ use handwriting_core::{ Cancellation, Error, FontBook, Limits, Parameters, RenderRequest, Result, document, generation::{self, Event, Output}, imaging, + local_fonts::{FontPage, FontSearch, LocalFonts}, }; use std::{ collections::HashMap, @@ -40,6 +41,7 @@ use tower_http::services::{ServeDir, ServeFile}; #[derive(Clone)] pub struct Config { + pub desktop: bool, pub data_dir: PathBuf, pub font_dir: PathBuf, pub web_dir: Option, @@ -54,6 +56,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + desktop: false, data_dir: PathBuf::from(".handwriting-rust"), font_dir: PathBuf::from("assets/font_assets"), web_dir: None, @@ -73,6 +76,7 @@ struct App { semaphore: Arc, fonts: Vec, font_cache: Mutex>>, + local_fonts: Option, rates: Mutex>, } #[derive(Clone)] @@ -109,7 +113,8 @@ impl IntoResponse for ApiError { type ApiResult = std::result::Result; impl Server { pub fn new(mut config: Config) -> Result { - if config.concurrency == 0 + if (config.desktop && config.access_token.as_ref().is_none_or(|t| t.len() < 32)) + || config.concurrency == 0 || config.max_active < config.concurrency || config.allowed_origins.is_empty() || config.allowed_origins.iter().any(|o| { @@ -149,7 +154,11 @@ impl Server { } let store = Store::open(&config.data_dir, config.ttl_seconds)?; let concurrency = config.concurrency; + let local_fonts = config + .desktop + .then(|| LocalFonts::new(Vec::new(), config.limits.max_file_bytes)); Ok(Self(Arc::new(App { + local_fonts, config, store: Mutex::new(store), semaphore: Arc::new(Semaphore::new(concurrency)), @@ -159,7 +168,7 @@ impl Server { }))) } pub fn router(&self) -> Router { - let api = Router::new() + let mut api = Router::new() .route("/health", get(health)) .route("/fonts_info", get(fonts)) .route("/version", get(version)) @@ -171,6 +180,11 @@ impl Server { .route("/generate_handwriting/task/{id}/cancel", post(cancel)) .route("/generate_handwriting/ws/{id}", get(websocket)) .fallback(|| async { StatusCode::NOT_FOUND }); + if self.0.local_fonts.is_some() { + api = api + .route("/local_fonts", post(local_fonts)) + .route("/local_fonts/read", post(read_local_font)); + } let mut app = Router::new().nest("/api", api); if let Some(dir) = &self.0.config.web_dir { app = app.fallback_service( @@ -424,9 +438,34 @@ async fn health() -> Json { async fn fonts(State(s): State) -> Json> { Json(s.0.fonts.clone()) } +async fn local_fonts( + State(s): State, + Json(query): Json, +) -> ApiResult> { + let page = + tokio::task::spawn_blocking(move || s.0.local_fonts.as_ref().unwrap().search(&query)) + .await + .map_err(storage_error)??; + Ok(Json(page)) +} +#[derive(serde::Deserialize)] +#[serde(deny_unknown_fields)] +struct FontId { + id: String, +} +async fn read_local_font( + State(s): State, + Json(request): Json, +) -> ApiResult> { + let (_, bytes) = + tokio::task::spawn_blocking(move || s.0.local_fonts.as_ref().unwrap().read(&request.id)) + .await + .map_err(storage_error)??; + Ok(bytes) +} async fn version(State(s): State) -> Json { Json( - serde_json::json!({"version":s.0.config.version,"capabilities":{"task_cancellation":true,"task_submission_id":true,"fine_edit":true}}), + serde_json::json!({"version":s.0.config.version,"capabilities":{"local_fonts":s.0.local_fonts.is_some(),"task_cancellation":true,"task_submission_id":true,"fine_edit":true}}), ) } struct Upload { @@ -1146,6 +1185,44 @@ mod tests { service.abort(); } #[tokio::test] + async fn local_fonts_require_authenticated_desktop_sidecar() { + let (_dir, hosted) = setup(); + let uri = "/api/local_fonts"; + let post = || { + Request::builder() + .method("POST") + .uri(uri) + .header("content-type", "application/json") + .body(Body::from("{}")) + .unwrap() + }; + let hosted_version: serde_json::Value = + serde_json::from_slice(&call(&hosted, "/api/version").await.1).unwrap(); + assert_eq!(hosted_version["capabilities"]["local_fonts"], false); + assert_eq!( + hosted.router().oneshot(post()).await.unwrap().status(), + StatusCode::NOT_FOUND + ); + let mut config = hosted.0.config.clone(); + config.desktop = true; + assert!(Server::new(config.clone()).is_err()); + config.access_token = Some("x".repeat(32)); + let desktop = Server::new(config).unwrap(); + assert_eq!( + desktop.router().oneshot(post()).await.unwrap().status(), + StatusCode::UNAUTHORIZED + ); + let mut foreign = post(); + foreign.headers_mut().insert( + "origin", + HeaderValue::from_static("https://elsewhere.example"), + ); + assert_eq!( + desktop.router().oneshot(foreign).await.unwrap().status(), + StatusCode::FORBIDDEN + ); + } + #[tokio::test] async fn static_health_fonts_version_and_unknown_api() { let (dir, s) = setup(); let (status, health) = call(&s, "/api/health").await; diff --git a/crates/handwriting-server/src/main.rs b/crates/handwriting-server/src/main.rs index 844b4f53..1837bb28 100644 --- a/crates/handwriting-server/src/main.rs +++ b/crates/handwriting-server/src/main.rs @@ -19,6 +19,12 @@ async fn main() -> Result<(), Box> { if !address.ip().is_loopback() && access_token.as_ref().is_none_or(|v| v.len() < 32) { return Err("非 loopback 监听必须配置至少 32 字节的 HANDWRITING_ACCESS_TOKEN".into()); } + let desktop = env::var("HANDWRITING_DESKTOP_SIDECAR").as_deref() == Ok("1"); + if desktop + && (!address.ip().is_loopback() || access_token.as_ref().is_none_or(|v| v.len() < 32)) + { + return Err("桌面 sidecar 需要 loopback 地址和至少 32 字节的访问令牌".into()); + } let listener = tokio::net::TcpListener::bind(address).await?; let bound = listener.local_addr()?; let root = env::current_exe()? @@ -26,6 +32,7 @@ async fn main() -> Result<(), Box> { .ok_or("无法定位服务程序目录")? .to_path_buf(); let mut config = Config { + desktop, access_token, ..Config::default() }; @@ -103,7 +110,6 @@ async fn main() -> Result<(), Box> { tracing::info!("服务地址:http://{bound};Rust 手写引擎已启用"); // 2026-10-12:桌面 sidecar 通过 stdin 管道跟随父进程生命周期。 // 专用线程避免 Tokio 的阻塞 stdin 在运行时退出时无法回收。 - let desktop = env::var("HANDWRITING_DESKTOP_SIDECAR").as_deref() == Ok("1"); let (parent_closed, parent_gone) = tokio::sync::oneshot::channel(); if desktop { std::thread::spawn(move || { diff --git a/crates/panache-mcp/Cargo.toml b/crates/panache-mcp/Cargo.toml index 9df6ee2e..67cca7cb 100644 --- a/crates/panache-mcp/Cargo.toml +++ b/crates/panache-mcp/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true publish.workspace = true [dependencies] -handwriting-core.workspace = true +handwriting-core = { workspace = true, features = ["local-fonts"] } tokio = { workspace = true, features = ["sync"] } rquickjs = "0.14" sha2 = "0.10.9" diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 0650a40f..947fdf38 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -52,7 +52,7 @@ cargo build --locked --release -p panache-mcp | 工具 | 用法 | | --- | --- | -| `list_fonts` | 列出本地字体。为作业、实验报告选笔迹时,指导模型展示中英数混排小样,按用户偏好定稿。 | +| `list_fonts` | 按名称、文件名或来源(`bundled`、`user`、`system`)检索字体。默认 20 项,使用 `next_offset` 翻页。为作业、实验报告选笔迹时,指导模型展示中英数混排小样,按用户偏好定稿。 | | `save_section` | 用 `markdown` 新建稿件。首次可传标题、字体、字号、纸样、墨色、种子和作业排版模式。返回 `draft_id`、版本号和节号。 | | `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 | | `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 | @@ -66,6 +66,10 @@ cargo build --locked --release -p panache-mcp | `annotate_review` | 将用户原话或模型观察挂到指定复盘 ID,保持稿件版本号。 | | `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 | +例如用 `list_fonts(query="楷", source="system", limit=8)` 检索系统字体。把 `entries[].id` 用于建稿的 `style.font` 或调稿的 `changes.font`。随包字体继续接受原文件名。个人和系统字体会随稿保存,删除源文件后仍可预览历史版本。TTF、OTF 和 TTC/OTC 中带轮廓、单个字面大小不超过 32 MiB 的字体可供选择。 + +桌面与 MCP 共享“我的字体”目录,`list_fonts` 的 `user_dir` 给出绝对路径。Windows 使用 `%LOCALAPPDATA%/Panache/fonts`,macOS 使用 `~/Library/Application Support/Panache/fonts`,Linux 使用 `$XDG_DATA_HOME/Panache/fonts`(默认 `~/.local/share/Panache/fonts`)。可通过 `PANACHE_USER_FONT_DIR` 指定绝对路径。把字体放入后调用 `list_fonts(source="user", refresh=true)`。 + 面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。 长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。 diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 34a6ce8f..754c36ff 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -218,6 +218,7 @@ impl Drafts { prepared: &str, new_style: Option<&Style>, paper: Option<&ImportedPaper>, + font: Option<&[u8]>, ) -> Result { let mut db = self.connect()?; let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; @@ -234,6 +235,12 @@ impl Drafts { serde_json::to_string(style)? ], )?; + if let Some(bytes) = font { + tx.execute( + "INSERT INTO draft_fonts VALUES(?,?,?)", + params![id, style.font, bytes], + )?; + } if let Some(paper) = paper { tx.execute( "INSERT INTO papers (draft,layout,image) VALUES (?1,?2,?3)", diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index d93cfbc6..279aa357 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -24,7 +24,7 @@ pub enum Format { #[derive(Clone, Serialize, Deserialize, JsonSchema)] #[serde(default, deny_unknown_fields)] pub struct Style { - /// Main font filename from list_fonts. English letters and digits follow it by default. + /// Main font ID from list_fonts. Bundled filenames remain valid. English letters and digits follow it by default. pub font: String, pub paper: Paper, /// RGB hex color, e.g. #302c30. diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index b199d0cb..eb51238c 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -12,7 +12,10 @@ mod tuning; use anyhow::{Context, Result, ensure}; use drafts::Drafts; use engine::Engine; -use handwriting_core::{Cancellation, Limits}; +use handwriting_core::{ + Cancellation, Limits, + local_fonts::{FontSearch, LocalFonts}, +}; use inputs::*; use rmcp::{ RoleServer, ServerHandler, ServiceExt, @@ -33,6 +36,7 @@ struct State { drafts: Drafts, engine: Mutex, fonts: Vec, + local_fonts: LocalFonts, storage: storage::Storage, worker: Arc, render_slot: Arc, @@ -41,6 +45,19 @@ struct State { #[derive(Clone)] struct Panache(Arc); +impl State { + fn import_catalog_font(&self, id: &str, revision: u32) -> Result)>> { + if self.fonts.iter().any(|f| f == id) { + return Ok(None); + } + let (entry, bytes) = self.local_fonts.read(id)?; + Ok(Some(( + format!("upload:{revision}:{}", entry.filename), + bytes, + ))) + } +} + fn reply(message: String, metadata: serde_json::Value) -> CallToolResult { let mut result = CallToolResult::success(vec![ContentBlock::text(message)]); result.structured_content = Some(metadata); @@ -116,7 +133,7 @@ impl Panache { || (input.paper_mode.is_none() && input.paper_guides.is_none()), "paper_mode and paper_guides require paper_path at creation" ); - let style = if input.draft_id.is_none() { + let mut style = if input.draft_id.is_none() { ensure!( input.expected_revision.unwrap_or(0) == 0 && input.section.unwrap_or(1) == 1, "A new draft starts at section 1" @@ -129,10 +146,6 @@ impl Panache { "Title too long" ); let style = input.style.clone().unwrap_or_default(); - ensure!( - self.0.fonts.contains(&style.font), - "Unknown font. Use list_fonts to choose an installed font." - ); style.ink_rgba()?; ensure!( (16..=72).contains(&style.font_size), @@ -176,13 +189,28 @@ impl Panache { } _ => None, }; - let _budget = paper - .as_ref() - .map(|p| state.storage.import(p.bytes.len())) + let font = match &mut style { + Some(style) => { + let font = state.import_catalog_font(&style.font, 1)?; + if let Some((handle, _)) = &font { + style.font.clone_from(handle); + } + font + } + None => None, + }; + let bytes = paper.as_ref().map_or(0, |p| p.bytes.len()) + + font.as_ref().map_or(0, |(_, data)| data.len()); + let _budget = (bytes > 0) + .then(|| state.storage.import(bytes)) .transpose()?; - state - .drafts - .save(&input, &prepared, style.as_ref(), paper.as_ref()) + state.drafts.save( + &input, + &prepared, + style.as_ref(), + paper.as_ref(), + font.as_ref().map(|(_, bytes)| bytes.as_slice()), + ) } }) .await??; @@ -310,26 +338,30 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - description = "List local fonts accepted by save_section and how to preview a coherent Chinese, English and digit sample." + description = "Search bundled, personal and system fonts by name/source. Results are paged. Use an entry ID in save_section style.font or tune_handwriting changes.font; user and system faces are saved with the draft." )] - fn list_fonts(&self) -> CallToolResult { - let names = self - .0 - .fonts - .iter() - .map(|name| format!("- {name}")) - .collect::>(); - let guidance = concat!( - "Select only the main font for a new draft. Its letters and digits are the default, including for homework and lab reports. ", - "For a hurried pen style, try 李国夫手写体.ttf if listed. Use a short line from the task with Chinese, an English term and a number or unit. ", - "Preview it at the intended size on the intended paper. Compare stroke weight, slant, relative size and digit legibility. ", - "If the style is undecided, show the sample, recommend a font based on what is visible, and ask if it fits before laying out the full page. ", - "Honor an approved or delegated main font. A request for generally messier handwriting applies to the main font. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." - ); - reply( - format!("{}\n\n{guidance}", names.join("\n")), - json!({"fonts": self.0.fonts, "sample_guidance": guidance}), - ) + async fn list_fonts(&self, Parameters(query): Parameters) -> CallToolResult { + let state = self.0.clone(); + let result = async { + let page = tokio::task::spawn_blocking(move || state.local_fonts.search(&query)).await??; + let names: Vec<_> = page.fonts.iter().map(|font| &font.id).collect(); + let guidance = concat!( + "Select only the main font for a new draft. Its letters and digits are the default, including for homework and lab reports. ", + "For a hurried pen style, try 李国夫手写体.ttf if listed. Use a short line from the task with Chinese, an English term and a number or unit. ", + "Preview it at the intended size on the intended paper. Compare stroke weight, slant, relative size and digit legibility. ", + "If the style is undecided, show the sample, recommend a font based on what is visible, and ask if it fits before laying out the full page. ", + "Honor an approved or delegated main font. A request for generally messier handwriting applies to the main font. Only consider separate settings for letters or digits when the user specifically requests them or expresses dissatisfaction with their appearance; then inspect describe_controls(group=typography)." + ); + let mut data = json!({ + "entries": page.fonts, "total": page.total, + "next_offset": page.next_offset, "user_dir": page.user_dir + }); + let message = format!("{data}\n\n{guidance}"); + data["fonts"] = json!(names); + data["sample_guidance"] = json!(guidance); + Ok(reply(message, data)) + }.await; + tool_result(result) } #[tool( @@ -659,6 +691,7 @@ async fn main() -> Result<()> { let state = State { storage: storage::Storage::open(&home, &drafts)?, drafts, + local_fonts: LocalFonts::new(engine.names.clone(), Limits::default().max_file_bytes), fonts: engine.names.clone(), engine: Mutex::new(engine), worker: fs::read_to_string(worker)?.into(), diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs index e46ef08e..aa3a4ad2 100644 --- a/crates/panache-mcp/src/tuning.rs +++ b/crates/panache-mcp/src/tuning.rs @@ -8,21 +8,6 @@ pub fn apply(state: &State, input: Tune) -> Result { let mut draft = state .drafts .snapshot(&input.draft_id, Some(input.expected_revision))?; - let mut changes = if input.changes.is_empty() { - draft.controls.clone() - } else { - let mut fonts = state.fonts.clone(); - if let Some(handle) = input - .changes - .get("font") - .and_then(|v| v.as_str()) - .filter(|s| s.starts_with("upload:")) - { - ensure!(draft.has_font(handle)?, "Unknown font for this draft"); - fonts.push(handle.to_owned()); - } - controls::merge(&draft.controls, &input.changes, &fonts)? - }; ensure!( input.note.as_ref().is_none_or(|s| s.chars().count() <= 320), "Note exceeds 320 characters" @@ -57,11 +42,35 @@ pub fn apply(state: &State, input: Tune) -> Result { draft.revision + 1, path.file_name().unwrap_or_default().to_string_lossy() ); - changes.insert("font".into(), json!(handle)); Some((handle, bytes)) + } else if let Some(id) = input + .changes + .get("font") + .and_then(|v| v.as_str()) + .filter(|id| !id.starts_with("upload:")) + { + state.import_catalog_font(id, draft.revision + 1)? } else { None }; + let mut patch = input.changes.clone(); + let mut fonts = state.fonts.clone(); + if let Some((handle, _)) = &font { + patch.insert("font".into(), json!(handle)); + fonts.push(handle.clone()); + } else if let Some(handle) = patch + .get("font") + .and_then(|v| v.as_str()) + .filter(|s| s.starts_with("upload:")) + { + ensure!(draft.has_font(handle)?, "Unknown font for this draft"); + fonts.push(handle.to_owned()); + } + let mut changes = if patch.is_empty() { + draft.controls.clone() + } else { + controls::merge(&draft.controls, &patch, &fonts)? + }; if let Some(guides) = &input.paper_guides { let paper = draft .paper diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 6baeeb9f..12564d81 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -169,11 +169,18 @@ async def ink_box(): async def smoke(command, arguments, out): with TemporaryDirectory() as temp: + personal = Path(temp) / "my-fonts" + personal.mkdir() + custom_font = personal / "LocalSample.ttf" + latin = Path(__file__).resolve().parents[2] / "handwriting-core/assets/latin" + shutil.copyfile(latin / "Handlee-Regular.ttf", custom_font) + second_font = personal / "SecondSample.ttf" + shutil.copyfile(latin / "IndieFlower-Regular.ttf", second_font) params = StdioServerParameters( command=command, args=arguments, cwd=temp, - env={**os.environ, "PANACHE_MCP_HOME": temp, "PATH": ""}, + env={**os.environ, "PANACHE_MCP_HOME": temp, "PANACHE_USER_FONT_DIR": str(personal), "PATH": ""}, ) async with stdio_client(params) as streams, ClientSession(*streams) as client: info = await client.initialize() @@ -203,6 +210,19 @@ async def smoke(command, arguments, out): guidance = listed.structuredContent["sample_guidance"] assert guidance in listed.content[0].text assert "志莽行书.ttf" in listed.structuredContent["fonts"] + results = (await call(client, "list_fonts", source="user", query="localsample", limit=1)).structuredContent + assert results["total"] == 1 and results["next_offset"] is None + entry = results["entries"][0] + assert entry["source"] == "user" and entry["filename"] == custom_font.name + saved_font = (await call(client, "save_section", markdown="ABC 123", style={"font": entry["id"]})).structuredContent + font_key = {"draft_id": saved_font["draft_id"]} + second = (await call(client, "list_fonts", source="user", query="secondsample")).structuredContent["entries"][0] + await call(client, "tune_handwriting", **font_key, expected_revision=1, changes={"font": second["id"]}) + font_previews = [png(await call(client, "preview_handwriting", **font_key, revision=r)) for r in (1, 2)] + assert font_previews[0] != font_previews[1] + custom_font.unlink() + second_font.unlink() + assert (await call(client, "list_fonts", source="user", refresh=True)).structuredContent["total"] == 0 paper_path = Path(temp) / "我的 横线纸.png" shutil.copyfile( Path(__file__).parent / "fixtures" / "ruled.png", paper_path @@ -589,6 +609,7 @@ async def progress(value, total, message=None): ) async with stdio_client(params) as streams, ClientSession(*streams) as client: await client.initialize() + assert [png(await call(client, "preview_handwriting", **font_key, revision=r)) for r in (1, 2)] == font_previews assert ( png( await call( From 674f0c2f4612f08fc7a6b79406060bc0b0964b08 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 22:21:21 +0800 Subject: [PATCH 3/5] =?UTF-8?q?feat(crates/handwriting-core):=20=E8=AF=BB?= =?UTF-8?q?=E5=8F=96=20PDF=20=E7=9A=84=E5=8E=9F=E9=A1=B5=E5=BA=95=E5=9B=BE?= =?UTF-8?q?=E5=92=8C=E5=8F=AF=E6=94=B9=E5=86=99=E6=96=87=E5=AD=97=E4=BD=8D?= =?UTF-8?q?=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:原有导入只提取正文字符串,分页、表格线和分栏位置无法传给排版器。 解决手段:通过 HTTP 和移动 FFI 按页返回底图、纸张尺寸和可改写的行框。保留扫描图、遮挡文字和无法可靠还原的内容,并在结果中提示。 收益:工作台可以在原位置填字或改写,隐藏的原文不会因为常见遮挡和透明效果被重新写到纸面上。 --- Cargo.lock | 398 +++++++++++++++- app/lib/services/licenses.dart | 2 + app/test/licenses_test.dart | 1 + assets/licenses/hayro-PDF-resources.txt | 189 ++++++++ crates/handwriting-bridge/src/api.rs | 11 +- crates/handwriting-bridge/src/tests.rs | 24 + crates/handwriting-core/Cargo.toml | 2 + crates/handwriting-core/src/lib.rs | 1 + crates/handwriting-core/src/pdf_page.rs | 161 +++++++ crates/handwriting-core/src/pdf_page/text.rs | 426 ++++++++++++++++++ .../src/pdf_page/visibility.rs | 95 ++++ crates/handwriting-core/tests/pdf_page.rs | 153 +++++++ crates/handwriting-server/src/lib.rs | 54 ++- 13 files changed, 1512 insertions(+), 5 deletions(-) create mode 100644 assets/licenses/hayro-PDF-resources.txt create mode 100644 crates/handwriting-core/src/pdf_page.rs create mode 100644 crates/handwriting-core/src/pdf_page/text.rs create mode 100644 crates/handwriting-core/src/pdf_page/visibility.rs create mode 100644 crates/handwriting-core/tests/pdf_page.rs diff --git a/Cargo.lock b/Cargo.lock index 91d5a1c6..10366be1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + [[package]] name = "adler2" version = "2.0.1" @@ -28,6 +34,21 @@ dependencies = [ "cpufeatures 0.2.17", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -58,6 +79,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -171,6 +198,27 @@ dependencies = [ "generic-array", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -279,6 +327,15 @@ dependencies = [ "inout", ] +[[package]] +name = "color" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ec7c5eb7a16992b1904d76c517d170ab353b0e0b3d5a0c81a8a0cd1037893cf" +dependencies = [ + "bytemuck", +] + [[package]] name = "color_quant" version = "1.1.0" @@ -496,6 +553,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + [[package]] name = "fallible-iterator" version = "0.3.0" @@ -529,6 +595,18 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "fearless_simd" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4beca3cb2444e3304ac30843cc091f44ed58932353cd492ce740067bfce6b12" + +[[package]] +name = "fearless_simd" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "629c9d6b6f30b5604089e0980f4d924a013aacb1654a6cdf5d3d852224f68651" + [[package]] name = "file-id" version = "0.2.3" @@ -785,6 +863,32 @@ version = "0.33.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4" +[[package]] +name = "glifo" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1218dedd5348c1b166ec3b8b3cbca49d2f527bd43b3fa072ea5123c523ed3f" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "png", + "skrifa 0.44.0", + "smallvec", + "vello_common", +] + +[[package]] +name = "guillotiere" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b17e70c989c36bad147b27a58d148c0741c51448aa5653436547323e524d0ab" +dependencies = [ + "euclid 0.22.14", +] + [[package]] name = "half" version = "2.7.1" @@ -817,10 +921,12 @@ dependencies = [ "flate2", "fontdb", "fontdue", + "hayro", "icu_properties", "image", "imageproc", "kamadak-exif", + "lopdf", "pdf-extract", "pdf-writer", "quick-xml", @@ -903,6 +1009,113 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "hayro" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34d3977ae664ab6eea015be3024379c83c6a3580f67d51be6884f1992bf683ba" +dependencies = [ + "ab_glyph_rasterizer", + "bytemuck", + "fearless_simd 1.2.0", + "hayro-interpret", + "image", + "kurbo", + "pic-scale", + "rustc-hash", + "vello_cpu", +] + +[[package]] +name = "hayro-ccitt" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46" + +[[package]] +name = "hayro-cmap" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a14afde3344be69225fec4f6f44f6a219a3a492f9d8301eb25ef608fe4b7014c" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-font" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ac7f0c78172573e9bd6eeb17f62c63f4d378b2a2d127c3ee9c2c7cc6fbdf78b" +dependencies = [ + "bitflags", + "hayro-cmap", + "hayro-syntax", + "kurbo", + "phf", + "rustc-hash", + "siphasher", + "skrifa 0.49.0", +] + +[[package]] +name = "hayro-interpret" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "166477622df4b770a0fc5889a9e4b48c7ff8595d6ec019bf71b4297b97b55fb6" +dependencies = [ + "bitflags", + "hayro-cmap", + "hayro-font", + "hayro-syntax", + "kurbo", + "moxcms", + "rustc-hash", + "siphasher", + "smallvec", +] + +[[package]] +name = "hayro-jbig2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840" +dependencies = [ + "fearless_simd 1.2.0", + "hayro-ccitt", +] + +[[package]] +name = "hayro-jpeg2000" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740" +dependencies = [ + "fearless_simd 1.2.0", +] + +[[package]] +name = "hayro-postscript" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc2d80da85f31c3fdc0366431f44cfd645a9da1e242ed1f4a61f213d9765660f" + +[[package]] +name = "hayro-syntax" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d" +dependencies = [ + "flate2", + "hayro-ccitt", + "hayro-jbig2", + "hayro-jpeg2000", + "memchr", + "rustc-hash", + "smallvec", + "zune-jpeg", +] + [[package]] name = "http" version = "1.5.0" @@ -1233,6 +1446,18 @@ dependencies = [ "mutate_once", ] +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid 0.22.14", + "polycool", + "smallvec", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1262,6 +1487,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1599,7 +1830,7 @@ dependencies = [ "adobe-cmap-parser", "cff-parser", "encoding_rs", - "euclid", + "euclid 0.20.14", "log", "lopdf", "postscript", @@ -1619,12 +1850,77 @@ dependencies = [ "ryu", ] +[[package]] +name = "peniko" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "839c8299360d2e998bdb106dc0a6cd71dcc5f4df51df1b620361bf50e283cca6" +dependencies = [ + "bytemuck", + "color", + "kurbo", + "linebender_resource_handle", + "smallvec", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pic-scale" +version = "0.7.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d76fd225dc3b8f089eaac369a74f57f557faffbd5da109ddd4e011010ab3ca10" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -1650,6 +1946,15 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + [[package]] name = "pom" version = "1.1.0" @@ -1809,6 +2114,31 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "read-fonts" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdaa4fffe9ff3ca2c353fa9729792805b9b3e324695ff5a081f860612e81b330" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "font-types", + "once_cell", + "smallvec", + "yoke", +] + [[package]] name = "read-fonts" version = "0.47.0" @@ -1953,6 +2283,12 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + [[package]] name = "rustix" version = "1.1.5" @@ -2178,6 +2514,35 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.49.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7459fb60888ad9a5f367dd293fa2fb9df142cb451aa6bfd6cd66a7d6a9b739d" +dependencies = [ + "bytemuck", + "once_cell", + "read-fonts 0.46.0", + "smallvec", + "yoke", +] + [[package]] name = "slab" version = "0.4.12" @@ -2651,6 +3016,35 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "vello_common" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c2fbe53548bcd25c8ff42f75a93770a8611a16b37bee56d7ef7b44e36027f1" +dependencies = [ + "bytemuck", + "fearless_simd 0.7.0", + "guillotiere", + "log", + "peniko", + "png", + "smallvec", + "thiserror", +] + +[[package]] +name = "vello_cpu" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed1fec424fbba6acf6cbc78bb526447eb77590d95f40419d598870fe37535212" +dependencies = [ + "bytemuck", + "glifo", + "hashbrown 0.17.1", + "png", + "vello_common", +] + [[package]] name = "version_check" version = "0.9.5" @@ -2911,7 +3305,7 @@ checksum = "944049531d52f9002812ea9de23ec8aa4e9577a7bee6869a1d0f297c679817ea" dependencies = [ "font-types", "log", - "read-fonts", + "read-fonts 0.47.0", ] [[package]] diff --git a/app/lib/services/licenses.dart b/app/lib/services/licenses.dart index 4c0b195b..0585d02e 100644 --- a/app/lib/services/licenses.dart +++ b/app/lib/services/licenses.dart @@ -5,6 +5,8 @@ void registerBundledLicenses() { LicenseRegistry.addLicense(() async* { const licenses = { 'Panache (AGPL-3.0-only)': 'Panache-AGPL-3.0.txt', + 'Hayro / PDFium standard fonts / Adobe CMaps / ICC profiles': + 'hayro-PDF-resources.txt', 'handwriting-web': 'project-MIT.txt', 'handright / handwriting-core': 'handright-BSD-3-Clause.txt', '霞鹜文楷 / LXGW WenKai': 'lxgw-wenkai-OFL.txt', diff --git a/app/test/licenses_test.dart b/app/test/licenses_test.dart index ac6070c5..d80b0e73 100644 --- a/app/test/licenses_test.dart +++ b/app/test/licenses_test.dart @@ -59,6 +59,7 @@ void main() { expect(text, contains('GNU AFFERO GENERAL PUBLIC LICENSE')); expect(text, contains('Copyright (c) 2025 Liuweiqing')); expect(text, contains('Chenghui LI')); + expect(text, contains('Copyright 2014 PDFium Authors')); expect(text, contains('SIL OPEN FONT LICENSE Version 1.1')); final workspace = Workspace(); diff --git a/assets/licenses/hayro-PDF-resources.txt b/assets/licenses/hayro-PDF-resources.txt new file mode 100644 index 00000000..4d9bc900 --- /dev/null +++ b/assets/licenses/hayro-PDF-resources.txt @@ -0,0 +1,189 @@ +Hayro PDF renderer + +Copyright (c) The Hayro Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +PDFium standard PDF fonts (original code copyright 2014 Foxit Software Inc.) + +// Copyright 2014 PDFium Authors. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Adobe character maps + +Copyright 1990-2023 Adobe. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. + +Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +Neither the name of Adobe nor the names of its contributors may be +used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +ICC colour profiles (hayro-interpret and hayro-jpeg2000) + +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see +http://creativecommons.org/publicdomain/zero/1.0/ diff --git a/crates/handwriting-bridge/src/api.rs b/crates/handwriting-bridge/src/api.rs index 280b87f7..e3d909d4 100644 --- a/crates/handwriting-bridge/src/api.rs +++ b/crates/handwriting-bridge/src/api.rs @@ -159,7 +159,7 @@ pub fn execute(mut request: Request) -> Result { "version" => Ok( json!({"version": handwriting_core::app_version(), "capabilities": {"fine_edit": true}}), ), - "import" | "identify" => { + "import" | "identify" | "pdf_page" => { let _operation = OPERATIONS .try_lock() .map_err(|_| Error::new("queue_full", "本地引擎正在处理任务"))?; @@ -176,7 +176,14 @@ pub fn execute(mut request: Request) -> Result { .get("file") .ok_or_else(|| Error::new("invalid_upload", "缺少文件"))?; let bytes = read(&upload.path)?; - if request.command == "import" { + if request.command == "pdf_page" { + serde_json::to_value(handwriting_core::pdf_page::import( + bytes, + &request.fields, + &limits(), + )?) + .map_err(io_error) + } else if request.command == "import" { Ok(json!({"text":document::extract(&upload.name, &bytes, &limits())?})) } else { let detected = diff --git a/crates/handwriting-bridge/src/tests.rs b/crates/handwriting-bridge/src/tests.rs index 4578270f..c5cd6b3c 100644 --- a/crates/handwriting-bridge/src/tests.rs +++ b/crates/handwriting-bridge/src/tests.rs @@ -61,6 +61,30 @@ fn local_engine_lifecycle_and_abi() { }; image::Rgba([shade, shade, shade, 255]) }); + let pdf_path = root.path().join("paper.pdf"); + let mut pdf = handwriting_core::export::PdfExport::new(); + pdf.add(&paper).unwrap(); + std::fs::write(&pdf_path, pdf.finish()).unwrap(); + let imported = call( + "pdf_page", + HashMap::from([("mode".into(), "fill".into())]), + HashMap::from([( + "file".into(), + Upload { + name: "paper.pdf".into(), + path: pdf_path, + }, + )]), + "", + ) + .unwrap(); + assert_eq!(imported["pageCount"], 1); + assert!( + imported["backgroundPng"] + .as_str() + .unwrap() + .starts_with("iVBOR") + ); let paper_path = root.path().join("paper.png"); paper.save(&paper_path).unwrap(); let expected = diff --git a/crates/handwriting-core/Cargo.toml b/crates/handwriting-core/Cargo.toml index 966e8132..fb43e01b 100644 --- a/crates/handwriting-core/Cargo.toml +++ b/crates/handwriting-core/Cargo.toml @@ -16,6 +16,8 @@ base64 = "0.23.1" flate2 = "1.1.10" fontdue = "0.9.4" image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "gif", "webp", "bmp", "tiff"] } +hayro = "0.9.0" +lopdf = { version = "0.42.0", default-features = false } icu_properties = "2.3.0" imageproc = { version = "0.27.0", default-features = false } kamadak-exif = "0.6.2" diff --git a/crates/handwriting-core/src/lib.rs b/crates/handwriting-core/src/lib.rs index df3b875c..a1cbed81 100644 --- a/crates/handwriting-core/src/lib.rs +++ b/crates/handwriting-core/src/lib.rs @@ -11,6 +11,7 @@ mod inline_document; pub mod local_fonts; pub use inline_document::{review_text, validate as validate_document}; mod parameters; +pub mod pdf_page; pub mod photo; pub mod render; pub mod text; diff --git a/crates/handwriting-core/src/pdf_page.rs b/crates/handwriting-core/src/pdf_page.rs new file mode 100644 index 00000000..4a385443 --- /dev/null +++ b/crates/handwriting-core/src/pdf_page.rs @@ -0,0 +1,161 @@ +use crate::{Error, Limits, Result}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use hayro::{ + PixmapSettings, RenderCache, + hayro_interpret::{InterpreterSettings, InterpreterWarning}, + hayro_syntax::{LoadPdfError, Pdf}, + vello_cpu::color::palette::css::WHITE, +}; +use lopdf::{Document, Stream, dictionary}; +use serde::Serialize; +use std::{ + collections::HashMap, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; + +mod text; +mod visibility; +pub use text::TextLine; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PdfPage { + pub page_count: usize, + pub page_index: usize, + pub width: u32, + pub height: u32, + pub page_width_pt: f32, + pub page_height_pt: f32, + pub background_png: String, + pub lines: Vec, + pub warnings: Vec<&'static str>, +} + +fn load(data: Vec) -> Result { + Pdf::new(data).map_err(|error| match error { + LoadPdfError::Decryption(_) => Error::new("encrypted_pdf", "PDF 需要解密"), + LoadPdfError::Invalid => Error::new("invalid_document", "无法读取 PDF"), + }) +} + +pub fn import( + bytes: Vec, + fields: &HashMap, + limits: &Limits, +) -> Result { + if bytes.len() > limits.max_file_bytes { + return Err(Error::new("upload_limit", "PDF 文件过大")); + } + let index = fields + .get("pageIndex") + .map_or("0", String::as_str) + .parse::() + .map_err(|_| Error::new("invalid_parameter", "PDF 页码无效"))?; + let layout = match fields.get("mode").map_or("layout", String::as_str) { + "layout" => true, + "fill" => false, + _ => return Err(Error::new("invalid_parameter", "PDF 导入模式无效")), + }; + let pdf = load(bytes)?; + let page_count = pdf.pages().len(); + if page_count > limits.max_pages { + return Err(Error::new("page_limit", "PDF 页数超过限制")); + } + let page = pdf + .pages() + .get(index) + .ok_or_else(|| Error::new("invalid_parameter", "PDF 页码超出范围"))?; + let (w, h) = page.render_dimensions(); + let unit = page.raw().get::(b"UserUnit").unwrap_or(1.0); + let (page_width_pt, page_height_pt) = (w * unit, h * unit); + if !page_width_pt.is_finite() + || !page_height_pt.is_finite() + || page_width_pt <= 0.0 + || page_height_pt <= 0.0 + { + return Err(Error::new("invalid_document", "PDF 页面尺寸无效")); + } + // 2026-11-23:按 144 DPI 生成底图,在扫描稿和超大画幅上按比例降低采样。 + let scale = (2.0 * unit).min(4096.0 / w.max(h)).min( + ((limits.max_pixels.min(4_000_000) as f64 / (f64::from(w) * f64::from(h))).sqrt()) as f32, + ); + if (w * scale) < 1.0 || (h * scale) < 1.0 { + return Err(Error::new("pixel_limit", "PDF 页面长宽比超过限制")); + } + let warning = Arc::new(AtomicBool::new(false)); + let sink = warning.clone(); + let settings = InterpreterSettings { + warning_sink: Arc::new(move |_: InterpreterWarning| { + sink.store(true, Ordering::Relaxed); + }), + ..Default::default() + }; + let mut extraction = text::extract(page, scale, &settings, limits)?; + let mut warnings = Vec::new(); + let mut edited = None; + if layout && let Some(stream) = extraction.background.take() { + // 2026-11-23:使用新内容流,仅修改所选页。共享的 Form、字体、图像及批注保持完整。 + edited = edit_background(pdf.data().as_ref(), index, stream); + if edited.is_none() { + extraction.lines.clear(); + extraction.unsupported = true; + } + } + let raster_page = edited + .as_ref() + .and_then(|p| p.pages().get(index)) + .unwrap_or(page); + let pixmap = hayro::render( + raster_page, + &RenderCache::new(), + &settings, + &Default::default(), + &PixmapSettings { + x_scale: scale, + y_scale: scale, + bg_color: WHITE, + }, + ); + if warning.load(Ordering::Relaxed) { + warnings.push("partial_render"); + } + if extraction.unsupported { + warnings.push("unsupported_text"); + } + if extraction.lines.is_empty() { + warnings.push("no_editable_text"); + } + let width = u32::from(pixmap.width()); + let height = u32::from(pixmap.height()); + let png = pixmap + .into_png() + .map_err(|e| Error::new("encode_failed", e.to_string()))?; + Ok(PdfPage { + page_count, + page_index: index, + width, + height, + page_width_pt, + page_height_pt, + background_png: STANDARD.encode(png), + lines: extraction.lines, + warnings, + }) +} + +fn edit_background(bytes: &[u8], index: usize, stream: Vec) -> Option { + let mut doc = Document::load_mem(bytes).ok()?; + let page = doc.page_iter().nth(index)?; + let id = doc.add_object(Stream::new(dictionary! {}, stream)); + doc.get_object_mut(page) + .ok()? + .as_dict_mut() + .ok()? + .set("Contents", id); + let mut output = Vec::new(); + doc.save_to(&mut output).ok()?; + load(output).ok() +} diff --git a/crates/handwriting-core/src/pdf_page/text.rs b/crates/handwriting-core/src/pdf_page/text.rs new file mode 100644 index 00000000..5e7bac14 --- /dev/null +++ b/crates/handwriting-core/src/pdf_page/text.rs @@ -0,0 +1,426 @@ +use super::visibility::Visibility; +use crate::{Error, Limits, Result}; +use hayro::{ + hayro_interpret::{ + BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, Image, ImageDrawProps, + InterpreterCache, InterpreterSettings, Paint, SoftMask, TransformExt, + font::{Glyph, GlyphRun}, + hayro_cmap::BfString, + interpret, + }, + hayro_syntax::{content::TypedIter, object::Dict, page::Page}, + kurbo::{Affine, BezPath, Rect, Shape}, +}; +use lopdf::{ + Object, + content::{Content, Operation}, +}; +use serde::Serialize; + +#[derive(Debug, Serialize)] +pub struct TextLine { + pub text: String, + pub x: f64, + pub y: f64, + pub width: f64, + pub height: f64, +} + +pub(super) struct Extraction { + pub lines: Vec, + pub background: Option>, + pub unsupported: bool, +} + +struct Candidate { + index: usize, + mode: i64, + lines: Vec, + supported: bool, +} + +struct Collector<'a> { + limits: &'a Limits, + target: Rect, + candidates: Vec, + current: Option, + marker_prefix: String, + characters: usize, + unsupported: bool, + oversized_image: bool, + clips: Vec>, + groups: Vec, + visibility: Visibility, +} + +fn show(operator: &str) -> bool { + matches!(operator, "Tj" | "TJ" | "'" | "\"") +} + +pub(super) fn extract( + page: &Page<'_>, + scale: f32, + settings: &InterpreterSettings, + limits: &Limits, +) -> Result { + let stream = page.page_stream().unwrap_or_default(); + if stream.len() as u64 > limits.max_archive_bytes { + return Err(Error::new("archive_limit", "PDF 页面内容流过大")); + } + let (w, h) = page.render_dimensions(); + let target = Rect::new( + 0.0, + 0.0, + (w * scale).floor() as f64, + (h * scale).floor() as f64, + ); + let cache = InterpreterCache::new(); + let mut context = Context::new( + Affine::scale(f64::from(scale)) * page.initial_transform(true).to_kurbo(), + target, + &cache, + page.xref(), + settings.clone(), + ); + let mut device = Collector { + limits, + target, + candidates: Vec::new(), + current: None, + marker_prefix: format!("Panache{:032x}-", rand::random::()), + characters: 0, + unsupported: false, + oversized_image: false, + clips: Vec::new(), + groups: Vec::new(), + visibility: Visibility::new(target.height()), + }; + // 2026-11-23:直接文字指令独立标记。嵌套表单、批注和不支持的字形仍由原 PDF 绘制。 + let mut original = page.operations(); + let mut has_inline_image = false; + let mut has_text = false; + let mut operators = 0usize; + while let Some(op) = original.next() { + operators += 1; + if operators > 200_000 { + return Err(Error::new("archive_limit", "PDF 页面绘图指令过多")); + } + let name: &[u8] = op.operator; + has_inline_image |= name == b"BI"; + has_text |= matches!(name, b"Tj" | b"TJ" | b"'" | b"\""); + } + let mut content = if has_text && !has_inline_image { + Content::decode(stream).ok() + } else { + None + }; + if let Some(parsed) = content.as_ref() { + // 2026-11-23:两种解析器必须读到相同的指令,才允许重写页面内容。 + let mut original = page.operations(); + if !parsed.operations.iter().all(|op| { + original + .next() + .is_some_and(|raw| &**raw.operator == op.operator.as_bytes()) + }) || original.next().is_some() + { + content = None; + } + } + if let Some(parsed) = content.as_ref() { + let mut marked = Vec::new(); + let mut mode = 0; + let mut saved = Vec::new(); + for (index, op) in parsed.operations.iter().enumerate() { + match op.operator.as_str() { + "Tr" => { + mode = op + .operands + .first() + .and_then(|o| o.as_i64().ok()) + .unwrap_or(-1) + } + "q" => saved.push(mode), + "Q" => mode = saved.pop().unwrap_or(0), + _ => {} + } + if show(&op.operator) && matches!(mode, 0 | 1) { + let number = device.candidates.len(); + device.candidates.push(Candidate { + index, + mode, + lines: Vec::new(), + supported: true, + }); + marked.push(Operation::new( + "BMC", + vec![Object::Name( + format!("{}{number}", device.marker_prefix).into_bytes(), + )], + )); + marked.push(op.clone()); + marked.push(Operation::new("EMC", vec![])); + } else { + marked.push(op.clone()); + } + } + let annotated = Content { operations: marked } + .encode() + .map_err(|e| Error::new("invalid_document", e.to_string()))?; + interpret( + TypedIter::new(&annotated), + page.resources(), + &mut context, + &mut device, + ); + } else { + interpret( + page.typed_operations(), + page.resources(), + &mut context, + &mut device, + ); + } + // 2026-11-23:批注外观和表单控件可能遮住正文。整页保留可避免暴露被覆盖的文字。 + if device.visibility.exhausted() + || page + .raw() + .get::>(b"Annots") + .is_some_and(|a| a.raw_iter().next().is_some()) + { + device.unsupported = true; + device.candidates.clear(); + } + if device.oversized_image { + return Err(Error::new("pixel_limit", "PDF 内嵌图像超过像素限制")); + } + if device.characters > limits.max_text_chars { + return Err(Error::new("text_limit", "PDF 页面文字过长")); + } + let mut lines = Vec::new(); + let mut background = None; + let mut accepted = device + .candidates + .into_iter() + .filter(|c| c.supported && !c.lines.is_empty()) + .peekable(); + if accepted.peek().is_some() + && let Some(content) = content + { + let mut output = Vec::new(); + for (index, op) in content.operations.into_iter().enumerate() { + if accepted.peek().is_some_and(|c| c.index == index) { + let item = accepted.next().unwrap(); + for line in item.lines { + append(&mut lines, line); + } + // 2026-11-23:让字形不可见但保留原字距、推进量和文字状态。 + output.push(Operation::new("Tr", vec![3.into()])); + output.push(op); + output.push(Operation::new("Tr", vec![item.mode.into()])); + } else { + output.push(op); + } + } + background = Some( + Content { operations: output } + .encode() + .map_err(|e| Error::new("invalid_document", e.to_string()))?, + ); + } + lines.retain(|line| !line.text.trim().is_empty()); + Ok(Extraction { + lines, + background, + unsupported: device.unsupported, + }) +} + +fn append(lines: &mut Vec, next: TextLine) { + if let Some(prev) = lines.last_mut() { + let gap = next.x - (prev.x + prev.width); + if (next.y - prev.y).abs() < next.height * 0.12 + && (next.height - prev.height).abs() < next.height * 0.12 + && gap >= -next.height * 0.18 + && gap < next.height * 0.65 + { + if gap > next.height * 0.14 + && !prev.text.ends_with(char::is_whitespace) + && !next.text.starts_with(char::is_whitespace) + { + prev.text.push(' '); + } + prev.width = (next.x + next.width - prev.x).max(prev.width); + prev.text.push_str(&next.text); + return; + } + } + lines.push(next); +} + +impl Collector<'_> { + fn solid(&self, props: &DrawProps<'_>) -> Option<[u8; 3]> { + if props.soft_mask.is_some() + || props.blend_mode != BlendMode::Normal + || self.groups.last() == Some(&false) + { + return None; + } + if let Paint::Color(color) = &props.paint + && let [r, g, b, 255] = color.to_rgba().to_rgba8() + { + Some([r, g, b]) + } else { + None + } + } + fn mark(&mut self, bounds: Rect, solid: Option<[u8; 3]>, text: Option) { + let bounds = bounds.intersect(self.target); + let clip = self.clips.last().copied().unwrap_or(Some(self.target)); + let solid = solid.filter(|_| clip.is_some_and(|r| r.contains_rect(bounds))); + self.visibility.paint(bounds, solid, text, |id| { + self.candidates[id].supported = false; + self.unsupported = true; + }); + } +} + +impl Device<'_> for Collector<'_> { + fn draw_glyph_run(&mut self, run: &GlyphRun<'_, '_>, props: DrawProps<'_>, mode: &DrawMode) { + if matches!(mode, DrawMode::Invisible) { + return; + } + let current = self.current.filter(|i| *i < self.candidates.len()); + let color = self.solid(&props); + let clip = self.clips.last().copied().unwrap_or(Some(self.target)); + for glyph in run.glyphs() { + let transform = props.transform * glyph.transform(); + let [a, b, c, d, x, baseline] = transform.as_coeffs(); + let height = -1000.0 * d; + let (width, ink) = match &**glyph { + Glyph::Outline(g) => ( + f64::from(g.advance_width().unwrap_or(500.0)) * a, + transform.transform_rect_bbox(g.outline().bounding_box()), + ), + Glyph::Type3(_) => { + if let Some(id) = current { + self.candidates[id].supported = false; + } + self.unsupported = true; + self.mark(self.target, None, None); + continue; + } + }; + let text = match glyph.as_unicode() { + Some(BfString::Char(c)) => c.to_string(), + Some(BfString::String(s)) => s, + None => String::new(), + }; + self.characters = self.characters.saturating_add(text.chars().count()); + if self.characters > self.limits.max_text_chars { + return; + } + let y = baseline - height * 0.8; + let rect = Rect::new(x, y, x + width, y + height); + if let Some(id) = current { + let geometry = rect.is_finite() + && height > 0.0 + && width > 0.0 + && b.abs() <= a.abs() * 0.02 + && c.abs() <= d.abs() * 0.02 + && clip.is_some_and(|r| { + r.contains_rect(rect) && (ink.area() == 0.0 || r.contains_rect(ink)) + }); + let valid_text = + !text.is_empty() && !text.contains(|c: char| c.is_control() || c == '\u{fffd}'); + let visible = color.is_some_and(|color| { + text.trim().is_empty() + || (ink.area() > 0.0 && self.visibility.visible(ink, color, id)) + }); + if geometry && valid_text && visible { + append( + &mut self.candidates[id].lines, + TextLine { + text, + x, + y, + width, + height, + }, + ); + } else { + self.candidates[id].supported = false; + self.unsupported = true; + } + } else { + self.unsupported = true; + } + self.mark(ink, None, current); + } + } + fn begin_marked_content(&mut self, tag: &[u8], _: Option<&Dict<'_>>) { + self.current = tag + .strip_prefix(self.marker_prefix.as_bytes()) + .and_then(|s| str::from_utf8(s).ok()) + .and_then(|s| s.parse().ok()); + } + fn end_marked_content(&mut self) { + self.current = None; + } + fn draw_image(&mut self, image: Image<'_, '_>, props: ImageDrawProps<'_>) { + self.oversized_image |= + u64::from(image.width()) * u64::from(image.height()) > self.limits.max_pixels; + let local = Rect::new(0.0, 0.0, image.width() as f64, image.height() as f64); + self.mark(props.transform.transform_rect_bbox(local), None, None); + } + fn draw_path(&mut self, path: &BezPath, props: DrawProps<'_>, mode: &DrawMode) { + let mut bounds = path.bounding_box(); + if let DrawMode::Stroke(stroke) | DrawMode::FillAndStroke(_, stroke) = mode { + let pad = f64::from(stroke.line_width.max(1.0) * stroke.miter_limit.max(1.0)) * 0.5; + bounds = bounds.inflate(pad, pad); + } + self.mark(props.transform.transform_rect_bbox(bounds), None, None); + } + fn draw_rect(&mut self, rect: &Rect, props: DrawProps<'_>, mode: &DrawMode) { + let [a, b, c, d, _, _] = props.transform.as_coeffs(); + if matches!(mode, DrawMode::Fill(_)) && ((a == 0.0 && d == 0.0) || (b == 0.0 && c == 0.0)) { + self.mark( + props.transform.transform_rect_bbox(*rect), + self.solid(&props), + None, + ); + } else { + self.draw_path(&rect.to_path(0.1), props, mode); + } + } + fn push_clip_path(&mut self, _: &ClipPath) { + self.clips.push(None); + } + fn push_clip_rect(&mut self, rect: &Rect) { + self.clips.push( + self.clips + .last() + .copied() + .unwrap_or(Some(self.target)) + .map(|r| r.intersect(*rect)), + ); + } + fn pop_clip(&mut self) { + self.clips.pop(); + } + fn push_transparency_group( + &mut self, + opacity: f32, + mask: Option>, + blend: BlendMode, + ) { + self.groups.push( + self.groups.last() != Some(&false) + && opacity == 1.0 + && mask.is_none() + && blend == BlendMode::Normal, + ); + } + fn pop_transparency_group(&mut self) { + self.groups.pop(); + } +} diff --git a/crates/handwriting-core/src/pdf_page/visibility.rs b/crates/handwriting-core/src/pdf_page/visibility.rs new file mode 100644 index 00000000..bcbbeda3 --- /dev/null +++ b/crates/handwriting-core/src/pdf_page/visibility.rs @@ -0,0 +1,95 @@ +use hayro::kurbo::Rect; + +// 2026-11-23:按绘制次序检查每行的背景色和后续遮挡;空间分桶避免逐字遍历整张纸。 +const ROW: f64 = 32.0; + +#[derive(Clone, Copy)] +struct Mark { + bounds: Rect, + solid: Option<[u8; 3]>, + text: Option, +} + +pub(super) struct Visibility { + rows: Vec>, + budget: usize, +} + +impl Visibility { + pub fn new(height: f64) -> Self { + Self { + rows: vec![Vec::new(); (height / ROW).ceil() as usize], + budget: 4_000_000, + } + } + fn rows_for(&self, bounds: Rect) -> std::ops::Range { + ((bounds.y0 / ROW).floor() as usize).min(self.rows.len()) + ..((bounds.y1 / ROW).ceil() as usize).min(self.rows.len()) + } + pub fn exhausted(&self) -> bool { + self.budget == 0 + } + pub fn visible(&mut self, bounds: Rect, ink: [u8; 3], candidate: usize) -> bool { + for idx in self.rows_for(bounds) { + let slice = Rect::new( + bounds.x0, + bounds.y0.max(idx as f64 * ROW), + bounds.x1, + bounds.y1.min((idx + 1) as f64 * ROW), + ); + let mut paper = [255; 3]; + for mark in self.rows[idx].iter().rev() { + self.budget = self.budget.saturating_sub(1); + if self.budget == 0 { + return false; + } + if mark.text == Some(candidate) || mark.bounds.intersect(slice).area() <= 0.0 { + continue; + } + let Some(color) = mark.solid.filter(|_| mark.bounds.contains_rect(slice)) else { + return false; + }; + paper = color; + break; + } + if ink.iter().zip(paper).all(|(i, b)| i.abs_diff(b) < 24) { + return false; + } + } + true + } + pub fn paint( + &mut self, + bounds: Rect, + solid: Option<[u8; 3]>, + text: Option, + mut cover: impl FnMut(usize), + ) { + if bounds.area() <= 0.0 || !bounds.is_finite() { + return; + } + for row in self.rows_for(bounds) { + if self.budget == 0 { + return; + } + let marks = &mut self.rows[row]; + for mark in marks.iter() { + self.budget = self.budget.saturating_sub(1); + if self.budget == 0 { + return; + } + if let Some(id) = mark.text + && Some(id) != text + && mark.bounds.intersect(bounds).area() > 0.0 + { + cover(id); + } + } + marks.push(Mark { + bounds, + solid, + text, + }); + } + } +} diff --git a/crates/handwriting-core/tests/pdf_page.rs b/crates/handwriting-core/tests/pdf_page.rs new file mode 100644 index 00000000..b57fe7a2 --- /dev/null +++ b/crates/handwriting-core/tests/pdf_page.rs @@ -0,0 +1,153 @@ +use base64::{Engine, engine::general_purpose::STANDARD}; +use handwriting_core::{ + Limits, + pdf_page::{self, PdfPage}, +}; +use lopdf::{Document, Stream, dictionary}; +use std::collections::HashMap; + +fn fixture(contents: &[&[u8]]) -> Vec { + let mut doc = Document::with_version("1.7"); + let pages = doc.new_object_id(); + let font = doc.add_object(dictionary! { + "Type" => "Font", + "Subtype" => "Type1", + "BaseFont" => "Helvetica", + "Encoding" => "WinAnsiEncoding", + }); + let mut kids = Vec::new(); + for stream in contents { + let content = doc.add_object(Stream::new(dictionary! {}, stream.to_vec())); + let id = doc.add_object(dictionary! { + "Type" => "Page", + "Parent" => pages, + "Contents" => content, + }); + kids.push(id.into()); + } + let resources = dictionary! { + "Font" => dictionary! {"F1" => font}, + "ExtGState" => dictionary! {"Hidden" => dictionary! {"ca" => 0.0f32}}, + }; + doc.objects.insert( + pages, + dictionary! { + "Type" => "Pages", + "Kids" => kids, + "Count" => contents.len() as i64, + "MediaBox" => vec![0.into(), 0.into(), 280.into(), 200.into()], + "CropBox" => vec![10.into(), 20.into(), 250.into(), 180.into()], + "Resources" => resources, + } + .into(), + ); + let catalog = doc.add_object(dictionary! {"Type"=>"Catalog","Pages"=>pages}); + doc.trailer.set("Root", catalog); + let mut out = Vec::new(); + doc.save_to(&mut out).unwrap(); + out +} + +fn page(pdf: &[u8], index: usize, mode: &str) -> PdfPage { + pdf_page::import( + pdf.to_vec(), + &HashMap::from([ + ("pageIndex".into(), index.to_string()), + ("mode".into(), mode.to_string()), + ]), + &Limits::default(), + ) + .unwrap() +} + +fn pixels(page: &PdfPage) -> image::RgbImage { + image::load_from_memory(&STANDARD.decode(&page.background_png).unwrap()) + .unwrap() + .to_rgb8() +} + +#[test] +fn selected_page_preserves_artwork_and_only_replaces_extractable_text() { + let pdf=fixture(&[ + b"1 0 0 rg 20 25 40 40 re f", + b"0.8 0.9 1 rg 10 20 240 160 re f 0 0 0 rg BT /F1 16 Tf 40 100 Td [(Exam) -200 (paper)] TJ ET BT /F1 12 Tf 0 1 -1 0 200 70 Tm (Vertical) Tj ET" + ]); + let layout = page(&pdf, 1, "layout"); + let fill = page(&pdf, 1, "fill"); + assert_eq!((layout.page_index, layout.page_count), (1, 2)); + assert_eq!((layout.width, layout.height), (480, 320)); + assert_eq!( + (layout.page_width_pt, layout.page_height_pt), + (240.0, 160.0) + ); + assert_eq!(layout.lines.len(), 1, "{:?}", layout.lines); + let line = &layout.lines[0]; + assert_eq!(line.text, "Exam paper"); + assert!((line.x - 60.0).abs() < 0.1 && (line.y - 134.4).abs() < 0.1); + assert!((line.height - 32.0).abs() < 0.1); + assert!(layout.warnings.contains(&"unsupported_text")); + let (back, original) = (pixels(&layout), pixels(&fill)); + let paper = *original.get_pixel(2, 2); + assert!(paper.0[0] < paper.0[2]); + assert!( + back.enumerate_pixels() + .any(|(x, y, p)| *p != *original.get_pixel(x, y)) + ); + for (x, y, p) in back.enumerate_pixels() { + if x < 310 { + assert_eq!(*p, paper); + } else { + assert_eq!(*p, *original.get_pixel(x, y)); + } + } + assert!( + back.enumerate_pixels() + .any(|(x, _, p)| x > 310 && p.0[0] < 150) + ); + let scanned = page(&pdf, 0, "layout"); + assert!(scanned.lines.is_empty() && scanned.warnings.contains(&"no_editable_text")); + assert_eq!(pixels(&scanned).get_pixel(30, 250).0, [255, 0, 0]); +} +#[test] +fn rejects_invalid_page_and_resource_limits() { + let pdf = fixture(&[b"BT /F1 12 Tf 40 40 Td (hello) Tj ET"]); + let fields = HashMap::from([("pageIndex".into(), "1".into())]); + assert_eq!( + pdf_page::import(pdf.clone(), &fields, &Limits::default()) + .unwrap_err() + .code, + "invalid_parameter" + ); + let limits = Limits { + max_text_chars: 2, + ..Default::default() + }; + assert_eq!( + pdf_page::import(pdf.clone(), &HashMap::new(), &limits) + .unwrap_err() + .code, + "text_limit" + ); + assert_eq!( + pdf_page::import(vec![0], &HashMap::new(), &limits) + .unwrap_err() + .code, + "invalid_document" + ); +} +#[test] +fn redacted_transparent_and_same_color_text_never_enter_the_editor() { + let pdf = fixture(&[b" + BT /F1 12 Tf 30 140 Td (Visible) Tj ET + BT /F1 12 Tf 30 100 Td (Covered) Tj ET + 0 g 45 98 25 16 re f + q /Hidden gs BT /F1 12 Tf 30 75 Td (Transparent) Tj ET Q + 1 g BT /F1 12 Tf 30 50 Td (White) Tj ET + "]); + for mode in ["fill", "layout"] { + let parsed = page(&pdf, 0, mode); + let labels: Vec<_> = parsed.lines.iter().map(|l| l.text.as_str()).collect(); + assert_eq!(labels, ["Visible"], "{mode}"); + assert!(parsed.warnings.contains(&"unsupported_text")); + } +} diff --git a/crates/handwriting-server/src/lib.rs b/crates/handwriting-server/src/lib.rs index 5083dbb6..fc7c131b 100644 --- a/crates/handwriting-server/src/lib.rs +++ b/crates/handwriting-server/src/lib.rs @@ -174,6 +174,7 @@ impl Server { .route("/version", get(version)) .route("/textfileprocess", post(textfile)) .route("/imagefileprocess", post(imagefile)) + .route("/pdfpageprocess", post(pdfpage)) .route("/generate_handwriting", post(submit)) .route("/generate_handwriting/task/{id}", get(status)) .route("/generate_handwriting/task/{id}/result", get(result)) @@ -766,6 +767,27 @@ async fn textfile( .map_err(|e| Error::new("worker_failed", e.to_string()))??; Ok(Json(serde_json::json!({"text":text}))) } +async fn pdfpage( + State(s): State, + Input(fields, mut files): Input, +) -> ApiResult> { + let file = files + .remove("file") + .ok_or_else(|| Error::new("invalid_upload", "缺少 file"))?; + let limits = s.0.config.limits.clone(); + let permit = + s.0.semaphore + .clone() + .try_acquire_owned() + .map_err(|_| Error::new("queue_full", "工作线程繁忙,请稍后重试"))?; + let page = tokio::task::spawn_blocking(move || { + let _permit = permit; + handwriting_core::pdf_page::import(file.bytes, &fields, &limits) + }) + .await + .map_err(|e| Error::new("worker_failed", e.to_string()))??; + Ok(Json(page)) +} async fn imagefile( State(s): State, Input(_, mut files): Input, @@ -895,7 +917,10 @@ async fn boundary(State(s): State, request: Request, next: Next) - .map(|v| v.0.ip().to_string()) .unwrap_or_else(|| "local".into()); let path = request.uri().path(); - let group = if path == "/api/generate_handwriting" || path.ends_with("fileprocess") { + let group = if path == "/api/generate_handwriting" + || path.ends_with("fileprocess") + || path == "/api/pdfpageprocess" + { "upload" } else { "query" @@ -1293,6 +1318,33 @@ mod tests { } } #[tokio::test] + async fn imports_selected_pdf_page() { + let (_dir, s) = setup(); + let mut pdf = export::PdfExport::new(); + pdf.add(&image_for_test()).unwrap(); + let bytes = pdf.finish(); + let (status, data) = send( + &s, + "/api/pdfpageprocess", + &[("pageIndex", "0"), ("mode", "fill")], + Some(("file", "paper.pdf", &bytes)), + ) + .await; + assert_eq!(status, StatusCode::OK, "{data}"); + assert_eq!(data["pageCount"], 1); + assert_eq!(data["pageIndex"], 0); + assert!(data["backgroundPng"].as_str().unwrap().starts_with("iVBOR")); + let (status, data) = send( + &s, + "/api/pdfpageprocess", + &[("pageIndex", "1")], + Some(("file", "paper.pdf", &bytes)), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + assert_eq!(data["error_code"], "invalid_parameter"); + } + #[tokio::test] async fn uploads_text_and_background_identification() { let (_dir, s) = setup(); let (status, data) = send( From 765611b9b2a7b90542381a921c86b71edb4ff28b Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 22:21:44 +0800 Subject: [PATCH 4/5] =?UTF-8?q?feat(app/workbench):=20=E5=9C=A8=20PDF=20?= =?UTF-8?q?=E5=8E=9F=E9=A1=B5=E4=B8=8A=E6=94=B9=E5=86=99=E6=96=87=E5=AD=97?= =?UTF-8?q?=E6=88=96=E6=A1=86=E9=80=89=E5=A1=AB=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:提取文字后重新排版适合普通正文,但双栏讲义和表单经常需要原来的位置与分页。 解决手段:导入时提供提取纯文本、按原页排手写与在原页上填字。后两种在逐页预览中编辑,使用选定的手写字体,按原纸张尺寸导出整本图片 PDF。 收益:同一个工作台既可重排文本,也能保留表格与分栏;使用者可在导出前核对每页,遇到扫描页可直接框选填写。 --- app/README.md | 1 + app/lib/l10n/app_en.arb | 25 + app/lib/l10n/app_zh.arb | 56 +++ .../screens/dialogs/pdf_import_dialog.dart | 57 +++ app/lib/screens/pdf_workbench.dart | 436 ++++++++++++++++++ app/lib/screens/workbench.dart | 33 +- app/lib/services/api.dart | 13 + app/lib/services/mobile_api.dart | 20 + app/lib/services/pdf_pages.dart | 241 ++++++++++ app/lib/widgets/pdf_writing_surface.dart | 172 +++++++ app/pubspec.lock | 40 ++ app/pubspec.yaml | 2 + app/test/pdf_workbench_test.dart | 386 ++++++++++++++++ 13 files changed, 1481 insertions(+), 1 deletion(-) create mode 100644 app/lib/screens/dialogs/pdf_import_dialog.dart create mode 100644 app/lib/screens/pdf_workbench.dart create mode 100644 app/lib/services/pdf_pages.dart create mode 100644 app/lib/widgets/pdf_writing_surface.dart create mode 100644 app/test/pdf_workbench_test.dart diff --git a/app/README.md b/app/README.md index a668e12e..bae17be1 100644 --- a/app/README.md +++ b/app/README.md @@ -10,6 +10,7 @@ UI 采用新艺术运动风格的 Material Design 3 主题,浅色使用暖白 - 桌面三栏工作台、手机分段工作台、中文/英文、系统主题及明暗切换。手机工具菜单显示图标、名称与用途说明,键盘展开时隐藏底部导航和导出操作。 - 长文本编辑、撤销/重做、TXT/DOCX/PDF/RTF 导入、插图及比例设置、分页和右对齐。 +- 导入 PDF 时可提取纯文本继续排版,也可在原页上操作。「按原页排手写」把可替换的文字写回原来的位置,保留分栏与表格线;「在原页上填字」允许在表格或扫描件上框选答题区。两种原页模式都按原尺寸导出图片 PDF,关闭前请先导出。 - Markdown 预览与清洗(四种表格格式)、LaTeX 公式预览与 Unicode 转换、常见 CircuiTikZ 电路手写绘制、中文书信排版。 - 工作台可选择内置字体,也可从文件导入 TTF / OTF。使用随桌面应用启动的本机引擎时,在「字体排版 → 本机字体库」可搜索系统字体。「我的字体 → 打开字体文件夹」适合一次添加多款字体,复制文件后点击刷新即可。该目录位于用户数据目录,升级应用时可保留。 - 背景上传、背景边距识别、全部现有排版/扰动/墨色/删除线参数。 diff --git a/app/lib/l10n/app_en.arb b/app/lib/l10n/app_en.arb index b63cb227..12c4c810 100644 --- a/app/lib/l10n/app_en.arb +++ b/app/lib/l10n/app_en.arb @@ -1,5 +1,30 @@ { "@@locale": "en", + "pdfImport": "Import PDF", + "pdfText": "Extract plain text", + "pdfTextHint": "Open selectable text in the workbench editor and reflow it on the current paper.", + "pdfLayout": "Rewrite in the original layout", + "pdfLayoutHint": "Replace readable lines with handwriting in place, keeping pages, columns and artwork. Scans retain their original appearance.", + "pdfFill": "Write on the original pages", + "pdfFillHint": "Keep the complete page image and draw answer areas. Works with scans.", + "pdfLocal": "Your local engine processes the file. Page modes export a flattened image PDF. Edits last until you close the document.", + "pdfRemote": "This file will be sent to the current engine at {engine}. Page modes export a flattened image PDF. Edits last until you close the document.", + "pdfLayoutHelp": "Tap a handwritten line to edit it. Export keeps each page’s print size.", + "pdfFillHelp": "Drag a rectangle to write in it. Tap an answer to edit or remove it.", + "pdfFontError": "The selected font could not be loaded. Choose a bundled font or a local font file in the workbench and retry.", + "pdfEncrypted": "This PDF is password protected. Export an unlocked copy in your PDF reader and import it again.", + "pdfLimit": "This document exceeds a file, page, complexity or export limit. Split it into smaller PDFs and retry.", + "pdfInvalid": "This PDF could not be read. Check the file or save a fresh copy from your PDF reader.", + "pdfEngineOld": "The current engine does not support PDF page import. Update the Panache engine or choose plain text.", + "pdfFailed": "PDF processing failed. {detail}", + "pdfCloseTitle": "Close this PDF?", + "pdfCloseHint": "Closing clears this editing session. Export the PDF first to keep the result.", + "pdfReview": "Review before exporting", + "pdfWarnings": "{pages} page(s) contain scans, text that could not be replaced or elements that might not render fully. Check those pages before saving.", + "pdfNoText": "No replaceable text on this page. Export keeps its image. Use “Write on the original pages” to add handwriting.", + "pdfPartial": "Some text or graphics could only be partially processed. Check this preview.", + "pdfProgress": "Exporting page {current} of {total}", + "pdfBoxText": "Text in this area", "appTitle": "Panache", "workspace": "Workspace", "guide": "Guide", diff --git a/app/lib/l10n/app_zh.arb b/app/lib/l10n/app_zh.arb index 3899a3ee..89e40bea 100644 --- a/app/lib/l10n/app_zh.arb +++ b/app/lib/l10n/app_zh.arb @@ -1,5 +1,61 @@ { "@@locale": "zh", + "pdfImport": "导入 PDF", + "pdfText": "提取纯文字", + "pdfTextHint": "把可复制的文字放入工作台编辑器,使用当前纸张重新排版。", + "pdfLayout": "按原页排手写", + "pdfLayoutHint": "按原页文字行的位置换成手写,保留分页、分栏和底图。扫描页保留原貌。", + "pdfFill": "在原页上填字", + "pdfFillHint": "完整保留页面图像,框选空白处填写。可用于扫描件。", + "pdfLocal": "文件由本机引擎处理。原页模式导出平面图像 PDF,关闭后清除本次编辑。", + "pdfRemote": "此文件将发送到当前引擎 {engine}。原页模式导出平面图像 PDF,关闭后清除本次编辑。", + "@pdfRemote": { + "placeholders": { + "engine": { + "type": "String" + } + } + }, + "pdfLayoutHelp": "点按手写行可以修改。导出时保留各页尺寸。", + "pdfFillHelp": "拖出矩形,输入内容。点按已填文字可以修改或移除。", + "pdfFontError": "无法载入所选字体。请返回工作台选择内置字体或本机字体文件后重试。", + "pdfEncrypted": "此 PDF 受密码保护。请在有权访问的 PDF 阅读器中导出未加密副本,再重新导入。", + "pdfLimit": "文件超过引擎或导出的大小、页数或复杂度上限。请拆分成较小的 PDF 后重试。", + "pdfInvalid": "无法读取该 PDF。请检查文件,或在 PDF 阅读器中重新另存一份。", + "pdfEngineOld": "当前引擎不支持 PDF 原页处理。请更新 Panache 引擎或选择提取纯文字。", + "pdfFailed": "PDF 处理失败。{detail}", + "@pdfFailed": { + "placeholders": { + "detail": { + "type": "String" + } + } + }, + "pdfCloseTitle": "关闭这份 PDF?", + "pdfCloseHint": "关闭后会清除本次编辑。如需保留成品,请先导出 PDF。", + "pdfReview": "检查导出页面", + "pdfWarnings": "有 {pages} 页含无法替换的文字、扫描内容或可能无法完整绘制的元素。请确认已查看这些页面。", + "@pdfWarnings": { + "placeholders": { + "pages": { + "type": "int" + } + } + }, + "pdfNoText": "该页没有可替换的文字。导出会保留原页图像。如需写字,请使用「在原页上填字」。", + "pdfPartial": "该页含部分无法替换的文字或无法完整绘制的元素,请核对预览。", + "pdfProgress": "正在导出第 {current} / {total} 页", + "@pdfProgress": { + "placeholders": { + "current": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "pdfBoxText": "区域文字", "appTitle": "Panache", "workspace": "工作台", "guide": "使用指南", diff --git a/app/lib/screens/dialogs/pdf_import_dialog.dart b/app/lib/screens/dialogs/pdf_import_dialog.dart new file mode 100644 index 00000000..854cb9ec --- /dev/null +++ b/app/lib/screens/dialogs/pdf_import_dialog.dart @@ -0,0 +1,57 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../services/pdf_pages.dart'; + +Future choosePdfImport(BuildContext context, String engine) { + final l = AppLocalizations.of(context)!; + final host = Uri.tryParse(engine)?.host ?? ''; + final local = + engine.startsWith('local://') || + ['localhost', '127.0.0.1', '::1'].contains(host); + return showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l.pdfImport), + content: SizedBox( + width: 480, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final choice in [ + (PdfImportMode.text, Icons.subject, l.pdfText, l.pdfTextHint), + ( + PdfImportMode.layout, + Icons.space_dashboard_outlined, + l.pdfLayout, + l.pdfLayoutHint, + ), + (PdfImportMode.fill, Icons.edit_note, l.pdfFill, l.pdfFillHint), + ]) + ListTile( + contentPadding: EdgeInsets.zero, + leading: Icon(choice.$2), + title: Text(choice.$3), + subtitle: Text(choice.$4), + onTap: () => Navigator.pop(context, choice.$1), + ), + const Divider(), + Text( + local ? l.pdfLocal : l.pdfRemote(engine), + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + ], + ), + ); +} diff --git a/app/lib/screens/pdf_workbench.dart b/app/lib/screens/pdf_workbench.dart new file mode 100644 index 00000000..20699e6a --- /dev/null +++ b/app/lib/screens/pdf_workbench.dart @@ -0,0 +1,436 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../services/api.dart'; +import '../services/pdf_pages.dart'; +import '../widgets/pdf_writing_surface.dart'; + +class PdfWorkbench extends StatefulWidget { + const PdfWorkbench({ + super.key, + required this.file, + required this.mode, + required this.fetch, + required this.loadFont, + required this.ink, + required this.save, + }); + final Upload file; + final PdfImportMode mode; + final Future Function(int index) fetch; + final Future Function() loadFont; + final Color ink; + final Future Function(Uint8List pdf) save; + + @override + State createState() => _PdfWorkbenchState(); +} + +class _PdfWorkbenchState extends State { + final edits = >{}; + final recentPages = {}; + PdfSourcePage? page; + int index = 0, count = 0; + int? exporting; + bool dirty = false, leaving = false; + String? family; + Object? failure; + + AppLocalizations get l => AppLocalizations.of(context)!; + bool get fill => widget.mode == PdfImportMode.fill; + Iterable relevantWarnings(PdfSourcePage source) => fill + ? source.warnings.where((w) => w == 'partial_render') + : source.warnings; + List boxesFor(PdfSourcePage source) => + edits[source.index] ?? (fill ? const [] : source.lines); + + @override + void initState() { + super.initState(); + load(0); + } + + Future readPage(int index) async { + final result = recentPages.remove(index) ?? await widget.fetch(index); + recentPages[index] = result; + while (recentPages.length > 1 && + (recentPages.length > 4 || + recentPages.values.fold( + 0, + (sum, page) => sum + page.paper.length, + ) > + 8 * 1024 * 1024)) { + recentPages.remove(recentPages.keys.first); + } + return result; + } + + Future load(int value) async { + setState(() { + index = value; + page = null; + failure = null; + }); + try { + family ??= await widget.loadFont(); + if (!mounted) return; + final result = await readPage(value); + if (mounted) { + setState(() { + page = result; + count = result.count; + }); + } + } catch (e) { + if (mounted) setState(() => failure = e); + } + } + + String errorText(Object e) { + if (family == null) return l.pdfFontError; + if (e is ApiException) { + return switch (e.code) { + 'encrypted_pdf' => l.pdfEncrypted, + 'archive_limit' || + 'upload_limit' || + 'page_limit' || + 'text_limit' || + 'pixel_limit' || + 'pdf_export_limit' => l.pdfLimit, + 'invalid_document' => l.pdfInvalid, + _ => + e.status == 404 || e.code == 'invalid_command' + ? l.pdfEngineOld + : l.pdfFailed(e.toString()), + }; + } + return l.pdfFailed(e.toString()); + } + + Future editBox(Rect rect, {int? at}) async { + final source = page; + if (source == null || exporting != null) return; + final boxes = boxesFor(source); + final previous = at == null ? null : boxes[at]; + final result = await showDialog( + context: context, + builder: (_) => _AnswerDialog( + initial: previous?.text ?? '', + existing: previous != null, + ), + ); + if (!mounted || result == null || result == previous?.text) return; + final next = [...boxes]; + if (result.trim().isEmpty) { + if (at == null) return; + next.removeAt(at); + } else { + final box = PdfWritingBox(rect, result, wrap: previous?.wrap ?? true); + if (at == null) { + next.add(box); + } else { + next[at] = box; + } + } + setState(() { + edits[index] = next; + dirty = true; + }); + } + + Future close() async { + if (dirty) { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l.pdfCloseTitle), + content: Text(l.pdfCloseHint), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: Text(l.close), + ), + ], + ), + ); + if (confirmed != true || !mounted) return; + } + setState(() => leaving = true); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) Navigator.pop(context); + }); + } + + Future export() async { + final current = page; + if (current == null || family == null || exporting != null) return; + setState(() => exporting = 0); + try { + final document = PdfPageExport(); + var issues = 0; + for (var i = 0; i < count; i++) { + if (!mounted || leaving) return; + setState(() => exporting = i + 1); + final source = i == current.index ? current : await readPage(i); + if (!mounted || leaving) return; + if (relevantWarnings(source).isNotEmpty || + (!fill && source.lines.isEmpty)) { + issues++; + } + final boxes = boxesFor(source); + final image = boxes.isEmpty + ? source.paper + : await renderPdfWritingPage(source, boxes, family!, widget.ink); + await document.add(source, image); + } + if (!mounted || leaving) return; + if (issues != 0) { + final confirmed = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l.pdfReview), + content: Text(l.pdfWarnings(issues)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(context, true), + child: Text(l.exportPdf), + ), + ], + ), + ); + if (!mounted || confirmed != true) return; + } + final bytes = await document.finish(); + if (!mounted || leaving) return; + await widget.save(bytes); + } catch (e) { + if (mounted) { + await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l.errorTitle), + content: Text(errorText(e)), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.close), + ), + ], + ), + ); + } + } finally { + if (mounted) setState(() => exporting = null); + } + } + + @override + Widget build(BuildContext context) { + final source = page; + final available = exporting == null; + final colors = Theme.of(context).colorScheme; + final warning = source == null + ? null + : !fill && source.lines.isEmpty + ? l.pdfNoText + : relevantWarnings(source).isNotEmpty + ? l.pdfPartial + : null; + return PopScope( + canPop: leaving || !dirty, + onPopInvokedWithResult: (popped, _) { + if (!popped) close(); + }, + child: Scaffold( + appBar: AppBar( + leading: IconButton( + tooltip: l.close, + icon: const Icon(Icons.close), + onPressed: close, + ), + title: Text(fill ? l.pdfFill : l.pdfLayout), + actions: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: FilledButton.icon( + onPressed: source != null && available ? export : null, + icon: const Icon(Icons.file_download_outlined), + label: Text(l.exportPdf), + ), + ), + ], + ), + body: SafeArea( + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.picture_as_pdf_outlined, + size: 18, + color: colors.primary, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + widget.file.name, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleSmall, + ), + ), + ], + ), + const SizedBox(height: 4), + Text(fill ? l.pdfFillHelp : l.pdfLayoutHelp), + if (warning != null) + Text(warning, style: TextStyle(color: colors.error)), + ], + ), + ), + const Divider(height: 1), + Expanded( + child: ColoredBox( + color: colors.surfaceContainerHighest, + child: Padding( + padding: const EdgeInsets.all(16), + child: Center( + child: exporting != null + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + const CircularProgressIndicator(), + const SizedBox(height: 12), + Text(l.pdfProgress(exporting!, count)), + ], + ) + : failure != null + ? Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + errorText(failure!), + textAlign: TextAlign.center, + ), + const SizedBox(height: 8), + OutlinedButton.icon( + onPressed: () => load(index), + icon: const Icon(Icons.refresh), + label: Text(l.retry), + ), + ], + ) + : source == null + ? const CircularProgressIndicator() + : PdfWritingSurface( + key: ValueKey(index), + page: source, + boxes: boxesFor(source), + family: family!, + ink: widget.ink, + fill: fill, + onAdd: (r) => editBox(r), + onEdit: (i) => + editBox(boxesFor(source)[i].rect, at: i), + ), + ), + ), + ), + ), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + IconButton( + tooltip: l.previousPage, + onPressed: + available && + index > 0 && + (page != null || failure != null) + ? () => load(index - 1) + : null, + icon: const Icon(Icons.chevron_left), + ), + Text(count == 0 ? '—' : '${index + 1} / $count'), + IconButton( + tooltip: l.nextPage, + onPressed: + available && + index + 1 < count && + (page != null || failure != null) + ? () => load(index + 1) + : null, + icon: const Icon(Icons.chevron_right), + ), + ], + ), + ], + ), + ), + ), + ); + } +} + +class _AnswerDialog extends StatefulWidget { + const _AnswerDialog({required this.initial, required this.existing}); + final String initial; + final bool existing; + @override + State<_AnswerDialog> createState() => _AnswerDialogState(); +} + +class _AnswerDialogState extends State<_AnswerDialog> { + late final controller = TextEditingController(text: widget.initial); + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + return AlertDialog( + title: Text(l.pdfBoxText), + content: SizedBox( + width: 380, + child: TextField( + controller: controller, + autofocus: true, + minLines: 1, + maxLines: 5, + maxLength: 2000, + ), + ), + actions: [ + if (widget.existing) + TextButton( + onPressed: () => Navigator.pop(context, ''), + child: Text(l.remove), + ), + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l.cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(context, controller.text), + child: Text(l.apply), + ), + ], + ); + } +} diff --git a/app/lib/screens/workbench.dart b/app/lib/screens/workbench.dart index e099a720..6e2c26ea 100644 --- a/app/lib/screens/workbench.dart +++ b/app/lib/screens/workbench.dart @@ -11,6 +11,9 @@ import '../l10n/app_localizations.dart'; import '../models/engine_failure.dart'; import 'dialogs/connection_dialog.dart'; import 'dialogs/illustration_dialog.dart'; +import 'dialogs/pdf_import_dialog.dart'; +import 'pdf_workbench.dart'; +import '../services/pdf_pages.dart'; import 'dialogs/local_font_dialog.dart'; import '../services/local_fonts.dart'; import 'dialogs/paper_area_dialog.dart'; @@ -328,7 +331,35 @@ class _WorkbenchState extends State with WidgetsBindingObserver { Future importText() => action(() async { final file = await pick(['txt', 'docx', 'pdf', 'rtf']); - if (file == null) return; + if (file == null || !mounted) return; + if (file.name.toLowerCase().endsWith('.pdf')) { + final api = w.api; + final mode = await choosePdfImport(context, api.base); + if (!mounted || mode == null) return; + if (mode != PdfImportMode.text) { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => PdfWorkbench( + file: file, + mode: mode, + ink: Color(w.settings.inkLook.color), + fetch: (index) async => PdfSourcePage.fromJson( + await api.pdfPage(file, index, mode.name), + index, + ), + loadFont: () => + loadPdfHandwritingFont(w.fontFile, w.settings.font), + save: (bytes) => saveBytes( + bytes, + 'pdf', + name: '${file.name.substring(0, file.name.length - 4)}-Panache', + ), + ), + ), + ); + return; + } + } await documents.importText(file); }); Future insertImage() => action(() async { diff --git a/app/lib/services/api.dart b/app/lib/services/api.dart index 4d84db36..4df0018b 100644 --- a/app/lib/services/api.dart +++ b/app/lib/services/api.dart @@ -96,6 +96,19 @@ class HandwritingApi { return jsonDecode(utf8.decode(response.bodyBytes)) as Map; } + Future> pdfPage( + Upload file, + int pageIndex, + String mode, + ) async { + final response = await multipart( + '/api/pdfpageprocess', + {'pageIndex': '$pageIndex', 'mode': mode}, + {'file': file}, + ); + return jsonDecode(utf8.decode(response.bodyBytes)) as Map; + } + Future submit( Map fields, Map files, { diff --git a/app/lib/services/mobile_api.dart b/app/lib/services/mobile_api.dart index 01705eb8..b1a39841 100644 --- a/app/lib/services/mobile_api.dart +++ b/app/lib/services/mobile_api.dart @@ -223,6 +223,26 @@ class MobileHandwritingApi extends HandwritingApi { } } + @override + Future> pdfPage( + Upload file, + int pageIndex, + String mode, + ) async { + final paths = await stage({'file': file}); + try { + return Map.from( + await call( + 'pdf_page', + fields: {'pageIndex': '$pageIndex', 'mode': mode}, + files: paths, + ) as Map, + ); + } finally { + await removeUploads(paths); + } + } + final Map> _uploads = {}; @override Future submit( diff --git a/app/lib/services/pdf_pages.dart b/app/lib/services/pdf_pages.dart new file mode 100644 index 00000000..63641990 --- /dev/null +++ b/app/lib/services/pdf_pages.dart @@ -0,0 +1,241 @@ +import 'dart:convert'; +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart' show compute; +import 'package:flutter/material.dart'; +import 'package:image/image.dart' as image; +import 'package:flutter/services.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; + +import 'api.dart'; + +enum PdfImportMode { text, layout, fill } + +class PdfWritingBox { + const PdfWritingBox(this.rect, this.text, {this.wrap = false}); + final Rect rect; + final String text; + final bool wrap; +} + +class PdfSourcePage { + const PdfSourcePage({ + required this.index, + required this.count, + required this.size, + required this.points, + required this.paper, + required this.lines, + required this.warnings, + }); + final int index, count; + final Size size, points; + final Uint8List paper; + final List lines; + final List warnings; + + factory PdfSourcePage.fromJson(Map json, int requested) { + double coordinate(dynamic value) { + if (value is! num || !value.isFinite) { + throw const FormatException('Invalid PDF coordinate'); + } + return value.toDouble(); + } + + final size = Size(coordinate(json['width']), coordinate(json['height'])); + final points = Size( + coordinate(json['pageWidthPt']), + coordinate(json['pageHeightPt']), + ); + final count = json['pageCount']; + if (size.isEmpty || + points.isEmpty || + size.width * size.height > 12000000 || + json['pageIndex'] != requested || + count is! int || + requested < 0 || + requested >= count) { + throw const FormatException('Invalid PDF page'); + } + final lines = []; + for (final item in json['lines'] as List) { + final area = Rect.fromLTWH( + coordinate(item['x']), + coordinate(item['y']), + coordinate(item['width']), + coordinate(item['height']), + ).intersect(Offset.zero & size); + final text = item['text'] as String; + if (!area.isEmpty && text.trim().isNotEmpty) { + lines.add(PdfWritingBox(area, text)); + } + } + return PdfSourcePage( + index: requested, + count: count, + size: size, + points: points, + paper: base64Decode(json['backgroundPng'] as String), + lines: lines, + warnings: List.from(json['warnings'] as List), + ); + } +} + +final _pdfFonts = >{}; + +Future loadPdfHandwritingFont(Upload? upload, String? selected) async { + final name = selected ?? '神韵英子楷书.ttf'; + final family = upload == null + ? 'PanachePDF-$name' + : 'PanachePDF-${sha256.convert(upload.bytes)}'; + try { + await _pdfFonts.putIfAbsent(family, () { + final data = upload == null + ? rootBundle.load('packages/handwriting_assets/font_assets/$name') + : Future.value(ByteData.sublistView(upload.bytes)); + return (FontLoader(family)..addFont(data)).load(); + }); + } catch (_) { + _pdfFonts.remove(family); + rethrow; + } + return family; +} + +/// Shared by the interactive page and the exported image. Original lines retain +/// their source bounding boxes; added answers may wrap across multiple lines. +void paintPdfWriting( + Canvas canvas, + Iterable boxes, + String family, + Color ink, +) { + for (final box in boxes) { + final area = box.rect; + final height = box.wrap ? math.min(area.height, 32.0) : area.height; + final painter = TextPainter( + text: TextSpan( + text: box.text, + style: TextStyle( + fontFamily: family, + fontFamilyFallback: const ['packages/handwriting_assets/LXGW WenKai'], + color: ink, + fontSize: height, + height: 1.0, + ), + ), + textDirection: TextDirection.ltr, + )..layout(maxWidth: box.wrap ? area.width : double.infinity); + if (painter.width > 0 && painter.height > 0) { + final scale = math.min( + 1.0, + math.min(area.width / painter.width, area.height / painter.height), + ); + canvas.save(); + canvas.clipRect(area); + canvas.translate( + area.left, + area.top + (box.wrap ? 0 : (area.height - painter.height * scale) / 2), + ); + canvas.scale(scale); + painter.paint(canvas, Offset.zero); + canvas.restore(); + } + painter.dispose(); + } +} + +Future renderPdfWritingPage( + PdfSourcePage page, + List boxes, + String family, + Color ink, +) async { + final codec = await ui.instantiateImageCodec(page.paper); + try { + final background = (await codec.getNextFrame()).image; + try { + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder); + canvas.drawImageRect( + background, + Rect.fromLTWH( + 0, + 0, + background.width.toDouble(), + background.height.toDouble(), + ), + Offset.zero & page.size, + Paint(), + ); + paintPdfWriting(canvas, boxes, family, ink); + final picture = recorder.endRecording(); + try { + final output = await picture.toImage( + page.size.width.round(), + page.size.height.round(), + ); + try { + final bytes = (await output.toByteData( + format: ui.ImageByteFormat.png, + ))!; + return bytes.buffer.asUint8List( + bytes.offsetInBytes, + bytes.lengthInBytes, + ); + } finally { + output.dispose(); + } + } finally { + picture.dispose(); + } + } finally { + background.dispose(); + } + } finally { + codec.dispose(); + } +} + +// Keep compressed image data for every page until the PDF is written. Holding +// raw RGBA surfaces for a large multipage document exhausts mobile memory. +Uint8List _encodePageJpeg(Uint8List png) { + final decoded = image.decodePng(png); + if (decoded == null) throw const FormatException('Invalid PDF page image'); + return image.encodeJpg(decoded, quality: 96); +} + +class PdfPageExport { + final _document = pw.Document(creator: 'Panache'); + int _imageBytes = 0; + + Future add(PdfSourcePage page, Uint8List png) async { + final jpeg = await compute(_encodePageJpeg, png); + _imageBytes += jpeg.length; + if (_imageBytes > 96 * 1024 * 1024) { + throw ApiException('PDF export limit', code: 'pdf_export_limit'); + } + final image = pw.MemoryImage(jpeg); + _document.addPage( + pw.Page( + pageFormat: PdfPageFormat( + page.points.width, + page.points.height, + marginAll: 0, + ), + build: (_) => pw.Image( + image, + width: page.points.width, + height: page.points.height, + fit: pw.BoxFit.fill, + ), + ), + ); + } + + Future finish() => _document.save(enableEventLoopBalancing: true); +} diff --git a/app/lib/widgets/pdf_writing_surface.dart b/app/lib/widgets/pdf_writing_surface.dart new file mode 100644 index 00000000..a15dd7ef --- /dev/null +++ b/app/lib/widgets/pdf_writing_surface.dart @@ -0,0 +1,172 @@ +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../services/pdf_pages.dart'; + +class PdfWritingSurface extends StatefulWidget { + const PdfWritingSurface({ + super.key, + required this.page, + required this.boxes, + required this.family, + required this.ink, + required this.fill, + required this.onAdd, + required this.onEdit, + }); + final PdfSourcePage page; + final List boxes; + final String family; + final Color ink; + final bool fill; + final ValueChanged onAdd; + final ValueChanged onEdit; + + @override + State createState() => _PdfWritingSurfaceState(); +} + +class _PdfWritingSurfaceState extends State { + Offset? start; + Rect? drag; + + @override + Widget build(BuildContext context) { + return LayoutBuilder( + builder: (_, constraints) { + final size = widget.page.size; + final scale = math.min( + constraints.maxWidth / size.width, + constraints.maxHeight / size.height, + ); + Offset position(Offset local) => Offset( + (local.dx / scale).clamp(0, size.width), + (local.dy / scale).clamp(0, size.height), + ); + return Center( + child: DecoratedBox( + decoration: const BoxDecoration( + color: Colors.white, + boxShadow: [ + BoxShadow( + color: Color(0x33000000), + blurRadius: 12, + offset: Offset(0, 3), + ), + ], + ), + child: GestureDetector( + key: const ValueKey('pdf-page-surface'), + dragStartBehavior: DragStartBehavior.down, + behavior: HitTestBehavior.opaque, + onPanStart: !widget.fill + ? null + : (d) => setState(() => start = position(d.localPosition)), + onPanUpdate: !widget.fill + ? null + : (d) { + if (start != null) { + setState( + () => drag = Rect.fromPoints( + start!, + position(d.localPosition), + ), + ); + } + }, + onPanCancel: () => setState(() { + start = null; + drag = null; + }), + onPanEnd: !widget.fill + ? null + : (_) { + final area = drag; + setState(() { + start = null; + drag = null; + }); + if (area != null && + area.width * scale >= 8 && + area.height * scale >= 6) { + widget.onAdd(area); + } + }, + onTapUp: (d) { + final point = position(d.localPosition); + final index = widget.boxes.lastIndexWhere( + (box) => box.rect.contains(point), + ); + if (index >= 0) widget.onEdit(index); + }, + child: SizedBox( + width: size.width * scale, + height: size.height * scale, + child: CustomPaint( + foregroundPainter: _WritingPainter( + widget.boxes, + widget.family, + widget.ink, + scale, + drag, + Theme.of(context).colorScheme.primary, + ), + child: Image.memory( + widget.page.paper, + fit: BoxFit.fill, + gaplessPlayback: false, + ), + ), + ), + ), + ), + ); + }, + ); + } +} + +class _WritingPainter extends CustomPainter { + const _WritingPainter( + this.boxes, + this.family, + this.ink, + this.scale, + this.drag, + this.selectionColor, + ); + final List boxes; + final String family; + final Color ink, selectionColor; + final double scale; + final Rect? drag; + @override + void paint(Canvas canvas, Size size) { + canvas.scale(scale); + paintPdfWriting(canvas, boxes, family, ink); + if (drag case final area?) { + canvas.drawRect( + area, + Paint()..color = selectionColor.withValues(alpha: .14), + ); + canvas.drawRect( + area, + Paint() + ..color = selectionColor + ..style = PaintingStyle.stroke + ..strokeWidth = 2 / scale, + ); + } + } + + @override + bool shouldRepaint(_WritingPainter old) => + old.boxes != boxes || + old.family != family || + old.ink != ink || + old.scale != scale || + old.drag != drag || + old.selectionColor != selectionColor; +} diff --git a/app/pubspec.lock b/app/pubspec.lock index beae6bd3..4c14bd29 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -25,6 +25,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" boolean_selector: dependency: transitive description: @@ -262,6 +278,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" + image: + dependency: "direct main" + description: + name: image + sha256: bc13f61f0f5cb77936e78ae5dae3800f442718dac5d2bc4654f03c239230ed0c + url: "https://pub.dev" + source: hosted + version: "4.13.1" integration_test: dependency: "direct dev" description: flutter @@ -497,6 +521,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.0" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: "6e40827f370d196e97c6611724d923a3d86c431ce8e2ce1e59edd03a67a1a6e6" + url: "https://pub.dev" + source: hosted + version: "3.13.1" petitparser: dependency: transitive description: @@ -561,6 +593,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.1" + qr: + dependency: transitive + description: + name: qr + sha256: "2c0189dca64a3ab08dda7acd7911c89af2374f08eb4eaded3e8ef4609f3b9c8b" + url: "https://pub.dev" + source: hosted + version: "3.0.3" record_use: dependency: transitive description: diff --git a/app/pubspec.yaml b/app/pubspec.yaml index b3ea5c68..509ab3b2 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -35,6 +35,8 @@ dependencies: panache_updater: path: updater super_clipboard: 0.9.1 + pdf: ^3.13.1 + image: ^4.13.1 dev_dependencies: flutter_test: diff --git a/app/test/pdf_workbench_test.dart b/app/test/pdf_workbench_test.dart new file mode 100644 index 00000000..cf279a06 --- /dev/null +++ b/app/test/pdf_workbench_test.dart @@ -0,0 +1,386 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/l10n/app_localizations.dart'; +import 'package:handwriting_app/screens/dialogs/pdf_import_dialog.dart'; +import 'package:handwriting_app/screens/pdf_workbench.dart'; +import 'package:handwriting_app/screens/workbench.dart'; +import 'package:handwriting_app/services/workspace.dart'; +import 'package:handwriting_app/services/api.dart'; +import 'package:handwriting_app/services/pdf_pages.dart'; +import 'package:handwriting_app/theme/handwriting_theme.dart'; +import 'package:handwriting_app/widgets/pdf_writing_surface.dart'; + +class _Picker extends FilePicker { + _Picker(this.result); + final FilePickerResult? result; + @override + Future pickFiles({ + String? dialogTitle, + String? initialDirectory, + FileType type = FileType.any, + List? allowedExtensions, + Function(FilePickerStatus)? onFileLoading, + bool allowCompression = false, + int compressionQuality = 0, + bool allowMultiple = false, + bool withData = false, + bool withReadStream = false, + bool lockParentWindow = false, + bool readSequential = false, + }) async { + return result; + } +} + +class _TextApi extends HandwritingApi { + _TextApi() : super('local://handwriting'); + @override + Future> importFile(String path, Upload file) async => { + 'text': 'Imported as text', + }; +} + +final _blank = base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAFUlEQVR4nGP8//8/AzbAhFV00EoAAFbUAw037MyjAAAAAElFTkSuQmCC', +); +Map sourceJson(int index) => { + 'pageCount': 2, + 'pageIndex': index, + 'width': 300, + 'height': 400, + 'pageWidthPt': 150.0, + 'pageHeightPt': 200.0, + 'backgroundPng': base64Encode(_blank), + 'warnings': [], + 'lines': [ + {'text': 'Left', 'x': 20, 'y': 15, 'width': 90, 'height': 18}, + {'text': 'Right', 'x': 160, 'y': 15, 'width': 90, 'height': 18}, + ], +}; + +Widget host( + Widget home, { + Locale locale = const Locale('en'), + GlobalKey? capture, +}) => MaterialApp( + debugShowCheckedModeBanner: false, + theme: handwritingTheme(Brightness.light), + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + builder: (_, child) => RepaintBoundary(key: capture, child: child), + home: home, +); + +Future drawAnswer( + WidgetTester tester, + Rect normalized, + String value, + String apply, +) async { + final rect = tester.getRect(find.byKey(const ValueKey('pdf-page-surface'))); + Offset at(Offset normalized) => + rect.topLeft + + Offset(normalized.dx * rect.width, normalized.dy * rect.height); + final gesture = await tester.startGesture(at(normalized.topLeft)); + await gesture.moveTo(at(normalized.center)); + await gesture.moveTo(at(normalized.bottomRight)); + await gesture.up(); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), value); + await tester.tap(find.text(apply)); + await tester.pumpAndSettle(); +} + +Future loadGalleryFonts() async { + for (final item in [ + ('MaterialIcons', 'fonts/MaterialIcons-Regular.otf'), + ( + 'packages/handwriting_assets/LXGW WenKai', + 'packages/handwriting_assets/font_assets/霞鹜文楷.ttf', + ), + ('Playfair Display', 'assets/fonts/PlayfairDisplay.ttf'), + ]) { + await (FontLoader(item.$1)..addFont(rootBundle.load(item.$2))).load(); + } +} + +void main() { + test('source pages keep physical dimensions, columns and the requested page identity', () { + final p = PdfSourcePage.fromJson(sourceJson(1), 1); + expect(p.points, const Size(150, 200)); + expect(p.lines[1].rect.left, 160); + expect(p.lines[0].rect.top, p.lines[1].rect.top); + expect( + () => PdfSourcePage.fromJson(sourceJson(1), 0), + throwsFormatException, + ); + }); + + test( + 'export produces two flattened PDF pages at their source print size', + () async { + final document = PdfPageExport(); + for (var i = 0; i < 2; i++) { + await document.add(PdfSourcePage.fromJson(sourceJson(i), i), _blank); + } + final bytes = await document.finish(); + final pdf = latin1.decode(bytes); + expect(pdf, startsWith('%PDF-')); + expect(RegExp(r'/Type\s*/Page\b').allMatches(pdf).length, 2); + expect( + RegExp(r'/MediaBox\s*\[\s*0\s+0\s+150\s+200\s*\]') + .allMatches(pdf) + .length, + 2, + ); + }, + ); + + testWidgets( + 'PDF importer discloses remote processing before choosing a mode', + (tester) async { + PdfImportMode? mode; + await tester.pumpWidget( + host( + Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () async => mode = await choosePdfImport( + context, + 'https://render.example', + ), + child: const Text('Open PDF'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open PDF')); + await tester.pumpAndSettle(); + expect(find.textContaining('https://render.example'), findsOneWidget); + expect(find.text('Extract plain text'), findsOneWidget); + expect(find.text('Rewrite in the original layout'), findsOneWidget); + await tester.tap(find.text('Write on the original pages')); + await tester.pumpAndSettle(); + expect(mode, PdfImportMode.fill); + }, + ); + + testWidgets( + 'answers stay on their own source page and closing protects edits', + (tester) async { + await tester.pumpWidget( + host( + PdfWorkbench( + file: Upload('form.pdf', Uint8List(0)), + mode: PdfImportMode.fill, + fetch: (i) async => PdfSourcePage.fromJson(sourceJson(i), i), + loadFont: () async => 'Ahem', + ink: Colors.black, + save: (_) async {}, + ), + ), + ); + await tester.pumpAndSettle(); + await drawAnswer( + tester, + const Rect.fromLTRB(.1, .15, .8, .27), + 'Answer A', + 'Apply', + ); + List answers() => tester + .widget(find.byType(PdfWritingSurface)) + .boxes; + expect(answers().single.text, 'Answer A'); + await tester.tap(find.byTooltip('Next')); + await tester.pumpAndSettle(); + expect(answers(), isEmpty); + await tester.tap(find.byTooltip('Previous')); + await tester.pumpAndSettle(); + expect(answers().single.text, 'Answer A'); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(find.text('Close this PDF?'), findsOneWidget); + }, + ); + + final gallery = Platform.environment['PANACHE_PDF_GALLERY']; + testWidgets( + 'workbench PDF selection offers all modes before plain-text import', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(470, 870); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final capture = GlobalKey(); + FilePicker.platform = _Picker( + FilePickerResult([ + PlatformFile( + name: 'lesson.PDF', + size: 4, + bytes: Uint8List.fromList([37, 80, 68, 70]), + ), + ]), + ); + addTearDown(() => FilePicker.platform = _Picker(null)); + final workspace = Workspace(api: _TextApi()) + ..connected = true + ..initialized = true; + addTearDown(workspace.dispose); + if (gallery != null) { + await tester.runAsync(loadGalleryFonts); + } + await tester.pumpWidget( + host( + Workbench( + workspace: workspace, + toggleLocale: () {}, + toggleTheme: () {}, + ), + locale: const Locale('zh'), + capture: capture, + ), + ); + await tester.pumpAndSettle(); + final l = AppLocalizations.of(tester.element(find.byType(Workbench)))!; + await tester.tap(find.byKey(const ValueKey('editor-tools'))); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(ListTile, l.importText)); + await tester.pumpAndSettle(); + expect(find.text(l.pdfLayout), findsOneWidget); + expect(find.text(l.pdfFill), findsOneWidget); + if (gallery != null) { + await tester.runAsync(() async { + final image = + await (capture.currentContext!.findRenderObject()! + as RenderRepaintBoundary) + .toImage(); + try { + final bytes = (await image.toByteData( + format: ui.ImageByteFormat.png, + ))!; + File('$gallery/ui-import.png') + .writeAsBytesSync(bytes.buffer.asUint8List()); + } finally { + image.dispose(); + } + }); + } + await tester.tap(find.text(l.pdfText)); + await tester.pumpAndSettle(); + expect(workspace.text, 'Imported as text'); + expect(tester.takeException(), isNull); + }, + ); + for (final mode in [PdfImportMode.layout, PdfImportMode.fill]) { + testWidgets( + 'render and export actual PDF pages in the ${mode.name} screen', + (tester) async { + tester.view.devicePixelRatio = 1; + tester.view.physicalSize = const Size(920, 960); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final family = await tester.runAsync(() async { + await loadGalleryFonts(); + return loadPdfHandwritingFont(null, '神韵英子楷书.ttf'); + }); + final capture = GlobalKey(); + var saved = false; + final sources = List.generate( + 2, + (i) => PdfSourcePage.fromJson( + jsonDecode(File('$gallery/${mode.name}-$i.json').readAsStringSync()) + as Map, + i, + ), + ); + await tester.pumpWidget( + host( + PdfWorkbench( + file: Upload('叶片的蒸腾作用.pdf', Uint8List(0)), + mode: mode, + fetch: (i) async => sources[i], + loadFont: () async => family!, + ink: const Color(0xff223e62), + save: (bytes) async { + File('$gallery/field-studies-${mode.name}.pdf') + .writeAsBytesSync(bytes); + saved = true; + }, + ), + locale: const Locale('zh'), + capture: capture, + ), + ); + await tester.pumpAndSettle(); + if (mode == PdfImportMode.fill) { + await tester.tap(find.byTooltip('下一页')); + await tester.pumpAndSettle(); + for (final answer in [ + (const Rect.fromLTRB(.077, .355, .90, .410), '叶片 A 与叶片 B'), + (const Rect.fromLTRB(.077, .54, .90, .594), '相同光照,分别置于通风处和静止空气中。'), + ( + const Rect.fromLTRB(.077, .733, .90, .82), + '通风处的水滴较多。空气流动加快了水分散失。', + ), + ]) { + await drawAnswer(tester, answer.$1, answer.$2, '应用'); + } + } + await tester.runAsync( + () => precacheImage( + MemoryImage(sources[mode == PdfImportMode.fill ? 1 : 0].paper), + tester.element(find.byType(PdfWritingSurface)), + ), + ); + await tester.pumpAndSettle(); + await tester.runAsync(() async { + final image = + await (capture.currentContext!.findRenderObject()! + as RenderRepaintBoundary) + .toImage(); + try { + final bytes = (await image.toByteData( + format: ui.ImageByteFormat.png, + ))!; + File('$gallery/ui-${mode.name}.png') + .writeAsBytesSync(bytes.buffer.asUint8List()); + } finally { + image.dispose(); + } + await tester.tap(find.text('导出 PDF')); + }); + for (var attempt = 0; attempt < 120; attempt++) { + await tester.pump(const Duration(milliseconds: 50)); + if (find.text('检查导出页面').evaluate().isNotEmpty) { + await tester.runAsync( + () => + tester.tap(find.widgetWithText(FilledButton, '导出 PDF').last), + ); + } + if (saved) { + break; + } + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 150)), + ); + } + expect(saved, isTrue); + expect( + File('$gallery/field-studies-${mode.name}.pdf').lengthSync(), + greaterThan(1500), + ); + expect(tester.takeException(), isNull); + }, + skip: gallery == null, + ); + } +} From 6a48b0dc683bbbbe63eaaed85e7892648834dc00 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Mon, 23 Nov 2026 22:23:22 +0800 Subject: [PATCH 5/5] =?UTF-8?q?fix(crates/handwriting-core):=20=E4=B8=AA?= =?UTF-8?q?=E4=BA=BA=E5=AD=97=E4=BD=93=E6=96=87=E4=BB=B6=E5=A4=B9=E4=B8=8D?= =?UTF-8?q?=E5=8F=AF=E7=94=A8=E6=97=B6=E4=BB=8D=E5=8F=AF=E9=80=89=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=AD=97=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:某些本机环境没有可写的用户目录,以前一次目录错误会让所有字体都无法搜索。 解决手段:单独保留个人目录的错误;其它来源仍然允许搜索和读取。工作台可处理缺省路径,重试个人库时重新检查目录。 收益:系统字体和内置字体可以继续使用,只有需要个人字体时才会提示修复目录。 --- .../screens/dialogs/local_font_dialog.dart | 6 +- app/lib/services/local_fonts.dart | 4 +- app/test/local_font_dialog_test.dart | 27 +++++++ crates/handwriting-core/src/local_fonts.rs | 71 +++++++++++-------- .../handwriting-core/src/local_fonts/tests.rs | 41 ++++++++++- 5 files changed, 114 insertions(+), 35 deletions(-) diff --git a/app/lib/screens/dialogs/local_font_dialog.dart b/app/lib/screens/dialogs/local_font_dialog.dart index 4cae770c..e92f2675 100644 --- a/app/lib/screens/dialogs/local_font_dialog.dart +++ b/app/lib/screens/dialogs/local_font_dialog.dart @@ -193,7 +193,11 @@ class _LocalFontDialogState extends State { return Column( children: [ SelectableText('${l.errorTitle}: $error'), - TextButton(onPressed: load, child: Text(l.retry)), + TextButton( + onPressed: () => + fonts.isEmpty ? reload(refresh: true) : load(), + child: Text(l.retry), + ), ], ); } diff --git a/app/lib/services/local_fonts.dart b/app/lib/services/local_fonts.dart index bca08371..d226db8a 100644 --- a/app/lib/services/local_fonts.dart +++ b/app/lib/services/local_fonts.dart @@ -9,7 +9,7 @@ typedef LocalFont = ({String id, String name, String filename}); typedef LocalFontPage = ({ List fonts, int? nextOffset, - String directory, + String? directory, }); extension LocalFonts on HandwritingApi { @@ -43,7 +43,7 @@ extension LocalFonts on HandwritingApi { ), ], nextOffset: data['next_offset'] as int?, - directory: data['user_dir'] as String, + directory: data['user_dir'] as String?, ); } diff --git a/app/test/local_font_dialog_test.dart b/app/test/local_font_dialog_test.dart index a3316ef2..c8c1e612 100644 --- a/app/test/local_font_dialog_test.dart +++ b/app/test/local_font_dialog_test.dart @@ -33,6 +33,33 @@ void main() { } }, ); + test( + 'system fonts stay selectable when the personal folder is unavailable', + () async { + final api = HandwritingApi( + 'http://localhost', + client: MockClient( + (_) async => http.Response( + jsonEncode({ + 'fonts': [ + {'id': 'sys', 'name': 'Kai', 'filename': 'kai.ttf'}, + ], + 'next_offset': null, + 'user_dir': null, + }), + 200, + ), + ), + ); + final page = await api.listLocalFonts( + source: LocalFontSource.system, + query: 'Kai', + ); + expect(page.fonts.single.name, 'Kai'); + expect(page.directory, isNull); + }, + ); + testWidgets( 'changing libraries discards outstanding searches and reads the selected font by ID', (tester) async { diff --git a/crates/handwriting-core/src/local_fonts.rs b/crates/handwriting-core/src/local_fonts.rs index 8693c26b..e9bd7d52 100644 --- a/crates/handwriting-core/src/local_fonts.rs +++ b/crates/handwriting-core/src/local_fonts.rs @@ -4,12 +4,7 @@ use fontdb::{Database, Source}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; -use std::{ - collections::HashSet, - env, fs, - path::{Path, PathBuf}, - sync::Mutex, -}; +use std::{collections::HashSet, env, fs, path::PathBuf, sync::Mutex}; use write_fonts::{FontBuilder, read::FontRef, types::Tag}; #[derive( @@ -48,7 +43,7 @@ pub struct FontPage { pub fonts: Vec, pub total: usize, pub next_offset: Option, - pub user_dir: PathBuf, + pub user_dir: Option, } struct Entry { @@ -59,6 +54,7 @@ struct Entry { struct Index { db: Database, + user_dir: std::result::Result, entries: Vec, } @@ -151,15 +147,26 @@ impl LocalFonts { } } - fn scan(&self, user_dir: &Path, system: impl FnOnce(&mut Database)) -> Result { - if !user_dir.is_absolute() { - return Err(invalid( - "PANACHE_USER_FONT_DIR must be an absolute directory", - )); + fn open_user_dir(&self) -> std::result::Result { + let dir = self + .user_dir + .as_deref() + .ok_or("Set PANACHE_USER_FONT_DIR to a writable directory")?; + if !dir.is_absolute() { + return Err("PANACHE_USER_FONT_DIR must be an absolute directory".into()); } - fs::create_dir_all(user_dir).map_err(|e| invalid(e.to_string()))?; + fs::create_dir_all(dir) + .and_then(|()| fs::read_dir(dir)) + .map_err(|e| format!("Cannot open personal font directory {}: {e}", dir.display()))?; + Ok(dir.into()) + } + + fn scan(&self, system: impl FnOnce(&mut Database)) -> Index { let mut db = Database::new(); - db.load_fonts_dir(user_dir); + let user_dir = self.open_user_dir(); + if let Ok(dir) = &user_dir { + db.load_fonts_dir(dir); + } let user_ids: HashSet<_> = db.faces().map(|f| f.id).collect(); system(&mut db); let mut entries = self @@ -248,26 +255,22 @@ impl LocalFonts { &b.info.id, )) }); - Ok(Index { db, entries }) + Index { + db, + user_dir, + entries, + } } - fn with_index( - &self, - refresh: bool, - visit: impl FnOnce(&Index, &Path) -> Result, - ) -> Result { - let dir = self - .user_dir - .as_deref() - .ok_or_else(|| invalid("Set PANACHE_USER_FONT_DIR to a writable directory"))?; + fn with_index(&self, refresh: bool, visit: impl FnOnce(&Index) -> Result) -> Result { let mut cache = self .index .lock() .map_err(|_| invalid("Font catalog unavailable"))?; if cache.is_none() || refresh { - *cache = Some(self.scan(dir, Database::load_system_fonts)?); + *cache = Some(self.scan(Database::load_system_fonts)); } - visit(cache.as_ref().unwrap(), dir) + visit(cache.as_ref().unwrap()) } pub fn search(&self, search: &FontSearch) -> Result { @@ -276,7 +279,12 @@ impl LocalFonts { return Err(invalid("Font search limit must be 1..100")); } let keyword = search.query.trim().to_lowercase(); - self.with_index(search.refresh, |index, dir| { + self.with_index(search.refresh, |index| { + if search.source == Some(FontSource::User) + && let Err(message) = &index.user_dir + { + return Err(invalid(message)); + } let mut fonts = Vec::new(); let mut total = 0; for entry in &index.entries { @@ -295,13 +303,18 @@ impl LocalFonts { fonts, total, next_offset: (end < total).then_some(end), - user_dir: dir.into(), + user_dir: index.user_dir.as_ref().ok().cloned(), }) }) } pub fn read(&self, id: &str) -> Result<(FontEntry, Vec)> { - self.with_index(false, |index, _| { + self.with_index(false, |index| { + if id.starts_with("user:") + && let Err(message) = &index.user_dir + { + return Err(invalid(message)); + } let entry = index .entries .iter() diff --git a/crates/handwriting-core/src/local_fonts/tests.rs b/crates/handwriting-core/src/local_fonts/tests.rs index bfdef0fb..2d99aea6 100644 --- a/crates/handwriting-core/src/local_fonts/tests.rs +++ b/crates/handwriting-core/src/local_fonts/tests.rs @@ -38,9 +38,7 @@ fn search_pages_sources_and_collection_face_bytes() { user_dir: Some(user.clone()), ..LocalFonts::new(vec!["sample.ttf".to_owned()], 110_000) }; - let index = catalog - .scan(&user, |db| db.load_fonts_dir(&system)) - .unwrap(); + let index = catalog.scan(|db| db.load_fonts_dir(&system)); *catalog.index.lock().unwrap() = Some(index); let first = catalog @@ -100,3 +98,40 @@ fn search_pages_sources_and_collection_face_bytes() { fs::remove_file(user.join("sample.ttf")).unwrap(); assert!(catalog.read(&personal[0].id).is_err()); } + +#[test] +fn unavailable_personal_directory_keeps_other_sources_usable() { + let home = tempdir().unwrap(); + let system_font = home.path().join("system.ttf"); + fs::write(&system_font, HANDLEE).unwrap(); + // An existing regular file prevents the personal directory from being created. + for path in [None, Some(system_font.join("fonts"))] { + let catalog = LocalFonts { + user_dir: path, + ..LocalFonts::new(vec!["bundled.ttf".into()], 50_000) + }; + let index = catalog.scan(|db| db.load_font_file(&system_font).unwrap()); + *catalog.index.lock().unwrap() = Some(index); + let results = catalog.search(&FontSearch::default()).unwrap(); + assert_eq!(results.total, 2); + assert!(results.user_dir.is_none()); + assert_eq!(results.fonts[0].id, "bundled.ttf"); + let system = catalog + .search(&FontSearch { + source: Some(FontSource::System), + ..Default::default() + }) + .unwrap(); + assert_eq!(catalog.read(&system.fonts[0].id).unwrap().1, HANDLEE); + let personal = catalog.search(&FontSearch { + source: Some(FontSource::User), + ..Default::default() + }); + let error = personal.err().unwrap(); + assert!(error.message.contains("directory")); + assert_eq!( + catalog.read("user:missing").err().unwrap().message, + error.message + ); + } +}