diff --git a/CHANGELOG.md b/CHANGELOG.md index d78f844f..2c136d6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## 未发布 +- 工作台切换清晰、均匀和渐变 PNG 时复用相同笔迹,方便在原位置比较柔化效果。 +- 精修后的 PDF 可直接导出并保留字形调整,即使 PNG 渐变的起点和终点暂时重合。 + - Linux x64 桌面包固定在 Ubuntu 24.04 构建,修复随包渲染服务与 MCP 在 Debian 13 上因要求 GLIBC_2.43 而无法启动的问题。 - 上传底纸后,纸张设置会直接显示从照片读到的制造商、设备型号、镜头和 ISO,缺少的项目仍可手动补填。 diff --git a/README.md b/README.md index 19cd2ef6..b1024cbf 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,16 @@ For text alone, paste the passage and say whether you want a printable page, wri [Handwritten poem](assets/examples/spring-at-qiantang-lake-6806782d66f9.webp) +### Handwriting on photographed paper + +Panache's MCP server laid out a sample STEM assignment on two photos of unruled paper. Select a page to open the full-resolution PNG. + +| Unruled paper on a wooden desk | Paper in shadow beside a flower | +| --- | --- | +| [![Handwritten code, basic blocks and a flowchart aligned with a tilted sheet on a wooden desk](assets/examples/angled-sheet-5ad065421e7c.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/922b6c7303c6a1d86271e42929bb316eb9c953bb/screenshots/worksheet-lettering/round-7/worksheet.png) | [![Handwritten assignment and flowchart on a shaded sheet with a flower overlapping the right edge](assets/examples/flower-shadow-a07835481c3a.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/1aea40070e551868368842392ca349a823d95de0/screenshots/worksheet-lettering/round-8/worksheet.png) | + +Original photographs · [Kaboompics](https://www.pexels.com/photo/empty-paper-sheet-on-wooden-table-4207708/) · [Andrzej Gdula](https://www.pexels.com/photo/white-printer-paper-on-brown-wooden-table-11485123/) + ## Contributing Report bugs in [GitHub Issues](https://github.com/SXP-Simon/Panache/issues). For local setup, tests, and pull requests, see [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 8e07e46b..301a3c71 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -46,6 +46,16 @@ Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 [《钱塘湖春行》](assets/examples/spring-at-qiantang-lake-6806782d66f9.webp) +### 在纸张照片上排版手写作业 + +一道模拟理工科作业,分别用 MCP 排在两张无横线的纸张照片上。点击成稿可查看原尺寸 PNG。 + +| 斜拍的无横线白纸 | 花影下的白纸 | +| --- | --- | +| [![木桌上的斜拍白纸,手写代码、基本块与流程图沿纸边排列](assets/examples/angled-sheet-5ad065421e7c.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/922b6c7303c6a1d86271e42929bb316eb9c953bb/screenshots/worksheet-lettering/round-7/worksheet.png) | [![花头遮住部分右侧纸边,手写作业与流程图避开花头](assets/examples/flower-shadow-a07835481c3a.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/1aea40070e551868368842392ca349a823d95de0/screenshots/worksheet-lettering/round-8/worksheet.png) | + +底图摄影 · [Kaboompics](https://www.pexels.com/photo/empty-paper-sheet-on-wooden-table-4207708/) · [Andrzej Gdula](https://www.pexels.com/photo/white-printer-paper-on-brown-wooden-table-11485123/) + ## 参与贡献 遇到问题可以到 [GitHub Issues](https://github.com/SXP-Simon/Panache/issues) 反馈。本地开发、测试和提交 PR 的说明见[贡献指南](CONTRIBUTING.md#中文贡献指南)。 diff --git a/app/lib/l10n/app_en.arb b/app/lib/l10n/app_en.arb index e2fe6bd2..563f1007 100644 --- a/app/lib/l10n/app_en.arb +++ b/app/lib/l10n/app_en.arb @@ -1,5 +1,18 @@ { "@@locale": "en", + "pngBlur": "PNG finish", + "pngBlurHint": "Soften the paper and ink together in previews, single PNGs and ZIP exports.", + "pngBlurOff": "Off", + "pngBlurUniform": "Uniform", + "pngBlurGradient": "Two-point gradient", + "pngBlurFrom": "Start A", + "pngBlurTo": "End B", + "pngBlurStrength": "Blur strength", + "pngBlurX": "Horizontal position", + "pngBlurY": "Vertical position", + "pngBlurTap": "Tap the page to move the selected point.", + "pngBlurDistinct": "Choose different start and end positions.", + "pngBlurFineHint": "To move or resize a letter, select Off above, then choose Fine edit in the preview.", "pdfImport": "Import PDF", "pdfText": "Extract plain text", "pdfTextHint": "Open selectable text in the workbench editor and reflow it on the current paper.", diff --git a/app/lib/l10n/app_zh.arb b/app/lib/l10n/app_zh.arb index 95ef1471..403b3750 100644 --- a/app/lib/l10n/app_zh.arb +++ b/app/lib/l10n/app_zh.arb @@ -1,5 +1,18 @@ { "@@locale": "zh", + "pngBlur": "PNG 成稿柔化", + "pngBlurHint": "柔化合成后的纸张与笔迹,适用于预览、单页 PNG 和 ZIP。", + "pngBlurOff": "关闭", + "pngBlurUniform": "均匀", + "pngBlurGradient": "两点渐变", + "pngBlurFrom": "起点 A", + "pngBlurTo": "终点 B", + "pngBlurStrength": "柔化强度", + "pngBlurX": "横向位置", + "pngBlurY": "纵向位置", + "pngBlurTap": "点按纸面可移动选中的点。", + "pngBlurDistinct": "起点和终点需要分开。", + "pngBlurFineHint": "想移动某个字或改它的大小?先在上方选「关闭」,再到预览区点「精细编辑」。", "pdfImport": "导入 PDF", "pdfText": "提取纯文字", "pdfTextHint": "把可复制的文字放入工作台编辑器,使用当前纸张重新排版。", diff --git a/app/lib/models/png_blur.dart b/app/lib/models/png_blur.dart new file mode 100644 index 00000000..e01f0248 --- /dev/null +++ b/app/lib/models/png_blur.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; + +enum PngBlurMode { off, uniform, gradient } + +class BlurAnchor { + BlurAnchor(this.x, this.y, this.sigma); + double x, y, sigma; + + Map toJson() => {'x': x, 'y': y, 'sigma_px': sigma}; + + static BlurAnchor? parse(Object? value) { + if (value case {'x': num x, 'y': num y, 'sigma_px': num sigma} + when x >= 0 && x <= 1 && y >= 0 && y <= 1 && sigma >= 0 && sigma <= 2) { + return BlurAnchor(x.toDouble(), y.toDouble(), sigma.toDouble()); + } + return null; + } +} + +class PngBlur { + PngBlurMode mode = PngBlurMode.off; + double uniform = .6; + BlurAnchor from = BlurAnchor(.5, 0, 1.2), to = BlurAnchor(.5, 1, 0); + + bool get valid => + mode != PngBlurMode.gradient || from.x != to.x || from.y != to.y; + bool get active => switch (mode) { + PngBlurMode.off => false, + PngBlurMode.uniform => uniform > 0, + PngBlurMode.gradient => from.sigma > 0 || to.sigma > 0, + }; + + Map toJson() => { + 'mode': mode.name, + 'uniform': uniform, + 'from': from.toJson(), + 'to': to.toJson(), + }; + + static PngBlur restore(Object? data) { + final blur = PngBlur(); + if (data is! Map) return blur; + blur.mode = + PngBlurMode.values.where((m) => m.name == data['mode']).firstOrNull ?? + PngBlurMode.off; + if (data['uniform'] case num v when v >= 0 && v <= 2) { + blur.uniform = v.toDouble(); + } + blur.from = BlurAnchor.parse(data['from']) ?? blur.from; + blur.to = BlurAnchor.parse(data['to']) ?? blur.to; + return blur; + } + + Map get fields => switch (mode) { + PngBlurMode.off => {}, + PngBlurMode.uniform => {'export_blur_px': '$uniform'}, + PngBlurMode.gradient => { + 'export_blur_gradient': jsonEncode({ + 'from': from.toJson(), + 'to': to.toJson(), + }), + }, + }; +} diff --git a/app/lib/models/settings.dart b/app/lib/models/settings.dart index 15b0a004..345b9042 100644 --- a/app/lib/models/settings.dart +++ b/app/lib/models/settings.dart @@ -1,4 +1,5 @@ import 'ink_page.dart'; +import 'png_blur.dart'; import 'render_parameter.dart'; export 'render_parameter.dart'; @@ -7,6 +8,7 @@ enum PaperStyle { blank, ruled, grid, dots } class Settings { Settings(); + PngBlur pngBlur = PngBlur(); /// A portrait exercise-book page sized for comfortable mobile previews. /// The usable area targets about twenty CJK characters and sixteen lines; @@ -104,6 +106,7 @@ class Settings { Map toJson() => { ...values, ...camera, + 'pngBlur': pngBlur.toJson(), 'fill': fill, 'layoutStyle': layoutStyle, 'font_option': font, @@ -126,6 +129,7 @@ class Settings { for (final entry in legacyFields.entries) if (json.containsKey(entry.key)) entry.value: json[entry.key], }; + pngBlur = PngBlur.restore(json['pngBlur']); _restoreCamera(json); for (final p in [...parameters, ...inkParameters]) { final value = p.valueFromDraft(json[p.key]); @@ -197,7 +201,9 @@ class Settings { String text, { required bool preview, required bool pdf, + bool supportsPngBlur = true, }) => { + if (!pdf && supportsPngBlur) ...{'seed': '0', ...pngBlur.fields}, ...values, ...camera, if (!strikethroughEnabled) 'strikethrough_probability': '0', diff --git a/app/lib/screens/workbench.dart b/app/lib/screens/workbench.dart index 76029be1..88e0875a 100644 --- a/app/lib/screens/workbench.dart +++ b/app/lib/screens/workbench.dart @@ -251,8 +251,9 @@ class _WorkbenchState extends State with WidgetsBindingObserver { void notify(String message) { if (mounted) { - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text(message))); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(message))); } } @@ -447,7 +448,8 @@ class _WorkbenchState extends State with WidgetsBindingObserver { return; } w.text = editor.text; - if (!preview && w.finePreviewNeedsRefresh) { + // PDF renders the current layout and its keyed fine edits in one request. + if (!preview && !pdf && w.finePreviewNeedsRefresh) { livePreview.markSubmitted(w.editRevision); final refreshed = await w.generate(); if (!mounted || !refreshed || w.previewStale) return; @@ -767,6 +769,7 @@ class _WorkbenchState extends State with WidgetsBindingObserver { fontFile: w.fontFile, background: w.background, settingsRevision: settingsRevision, + supportsPngBlur: w.api.supportsPngBlur, locked: editingLocked, activeSection: settingsSection, onSectionChanged: wide ? null : selectSettingsSection, @@ -873,7 +876,10 @@ class _WorkbenchState extends State with WidgetsBindingObserver { pages: w.pages, inkPages: w.inkPages, inkLook: w.settings.inkLook, - onFineEdit: w.api.supportsFineEdit && editor.text.trim().isNotEmpty + onFineEdit: + !w.pngBlurActive && + w.api.supportsFineEdit && + editor.text.trim().isNotEmpty ? enterFineEdit : null, fineAdjustments: w.fineAdjustments, diff --git a/app/lib/services/api.dart b/app/lib/services/api.dart index 45505e05..17366770 100644 --- a/app/lib/services/api.dart +++ b/app/lib/services/api.dart @@ -144,11 +144,16 @@ class HandwritingApi { bool get supportsCancel => _supportsCancel; bool supportsLocalFonts = false; bool supportsFineEdit = false; + bool supportsPngBlur = false; void configureCapabilities(dynamic info) { supportsLocalFonts = info is Map && info['capabilities'] is Map && info['capabilities']['local_fonts'] == true; + supportsPngBlur = + info is Map && + info['capabilities'] is Map && + info['capabilities']['export_blur'] == true; supportsFineEdit = info is Map && info['capabilities'] is Map && diff --git a/app/lib/services/engine_contract.dart b/app/lib/services/engine_contract.dart index d9bc59c5..f2eb7f87 100644 --- a/app/lib/services/engine_contract.dart +++ b/app/lib/services/engine_contract.dart @@ -62,11 +62,12 @@ class EngineInfo { required this.canCancel, required this.canChooseTaskId, this.canFineEdit = false, + this.canBlurPng = false, this.canListLocalFonts = false, }); final String version; final bool canCancel, canChooseTaskId; - final bool canFineEdit, canListLocalFonts; + final bool canFineEdit, canListLocalFonts, canBlurPng; factory EngineInfo.fromJson(Map value) { final capabilities = value['capabilities']; return EngineInfo( @@ -77,6 +78,7 @@ class EngineInfo { capabilities is Map && capabilities['task_submission_id'] == true, canListLocalFonts: capabilities is Map && capabilities['local_fonts'] == true, + canBlurPng: capabilities is Map && capabilities['export_blur'] == true, canFineEdit: capabilities is Map && capabilities['fine_edit'] == true, ); } diff --git a/app/lib/services/engine_gateway.dart b/app/lib/services/engine_gateway.dart index 4c8cfd2b..8597a7da 100644 --- a/app/lib/services/engine_gateway.dart +++ b/app/lib/services/engine_gateway.dart @@ -25,6 +25,7 @@ class ApiEngineGateway implements EngineGateway, EngineCatalog { 'capabilities': { 'task_cancellation': info.canCancel, 'task_submission_id': info.canChooseTaskId, + 'export_blur': info.canBlurPng, 'fine_edit': info.canFineEdit, 'local_fonts': info.canListLocalFonts, }, diff --git a/app/lib/services/workspace.dart b/app/lib/services/workspace.dart index 2b63b3f9..26eecd38 100644 --- a/app/lib/services/workspace.dart +++ b/app/lib/services/workspace.dart @@ -47,6 +47,7 @@ class Workspace extends ChangeNotifier { Settings settings; String text = '', version = ''; bool fineEnabled = false; + bool get pngBlurActive => api.supportsPngBlur && settings.pngBlur.active; final _fineHistory = FineEditHistory(); String? get _finePageKey => inkPages.elementAtOrNull(page)?.fine?.key; bool get canFineUndo => _fineHistory.canStep(text, _finePageKey, redo: false); @@ -285,7 +286,7 @@ class Workspace extends ChangeNotifier { void edit({bool inkOnly = false}) { if (disposed) return; - if (!inkOnly || !initialized) ++_editRevision; + if (!inkOnly || pngBlurActive || !initialized) ++_editRevision; if (inkOnly) exportBytes = null; saveTimer?.cancel(); saveTimer = Timer(const Duration(milliseconds: 400), persist); @@ -384,6 +385,7 @@ class Workspace extends ChangeNotifier { } if (text.trim().isEmpty || !settings.valid || + (!pdf && api.supportsPngBlur && !settings.pngBlur.valid) || (fontFile == null && settings.font == null)) { if (!live) { error = 'validation'; @@ -396,12 +398,13 @@ class Workspace extends ChangeNotifier { expandImages(text, images), preview: preview, pdf: pdf, + supportsPngBlur: api.supportsPngBlur, ); if (fineEnabled && api.supportsFineEdit) { fields['fine_edit'] = 'true'; fields['seed'] = '0'; final fineEdits = _fineHistory.forText(text); - if (!preview && fineEdits != null) { + if ((!preview || pngBlurActive) && fineEdits != null) { fields['fine_edits'] = jsonEncode(fineEdits.toJson()); } } diff --git a/app/lib/widgets/settings/paper_settings.dart b/app/lib/widgets/settings/paper_settings.dart index 3d7fcf5f..3c387d2a 100644 --- a/app/lib/widgets/settings/paper_settings.dart +++ b/app/lib/widgets/settings/paper_settings.dart @@ -6,11 +6,13 @@ import '../../models/upload.dart'; import '../../utils/paper_exif.dart'; import '../paper_style_picker.dart'; import 'settings_fields.dart'; +import 'png_blur_settings.dart'; List paperSettings( AppLocalizations l, SettingsFields fields, { required Upload? background, + required bool supportsPngBlur, required VoidCallback onUploadBackground, required VoidCallback onRemoveBackground, required VoidCallback onDetectBackground, @@ -78,6 +80,10 @@ List paperSettings( ), if (background != null) _paperCamera(l, fields, background), ], collapsible: false), + if (supportsPngBlur) + settingsGroup('png-blur', l.pngBlur, Icons.blur_on, [ + PngBlurSettings(fields: fields, background: background), + ], collapsible: false), settingsGroup('dimensions', l.paperSizeAndMargins, Icons.space_bar, [ fields.parameterGrid( parameters.where( diff --git a/app/lib/widgets/settings/png_blur_settings.dart b/app/lib/widgets/settings/png_blur_settings.dart new file mode 100644 index 00000000..a7ae2256 --- /dev/null +++ b/app/lib/widgets/settings/png_blur_settings.dart @@ -0,0 +1,229 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import '../../models/png_blur.dart'; +import '../../models/upload.dart'; +import 'settings_fields.dart'; + +class PngBlurSettings extends StatefulWidget { + const PngBlurSettings({super.key, required this.fields, this.background}); + final SettingsFields fields; + final Upload? background; + + @override + State createState() => _PngBlurSettingsState(); +} + +class _PngBlurSettingsState extends State { + bool start = true; + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context)!; + final fields = widget.fields; + final blur = fields.settings.pngBlur; + final anchor = start ? blur.from : blur.to; + final labels = { + PngBlurMode.off: l.pngBlurOff, + PngBlurMode.uniform: l.pngBlurUniform, + PngBlurMode.gradient: l.pngBlurGradient, + }; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(l.pngBlurHint), + Wrap( + spacing: 6, + children: [ + for (final mode in labels.keys) + ChoiceChip( + key: ValueKey('png-blur-${mode.name}'), + label: Text(labels[mode]!), + selected: blur.mode == mode, + onSelected: fields.edited((_) => blur.mode = mode), + ), + ], + ), + if (blur.mode == PngBlurMode.gradient) ...[ + const SizedBox(height: 8), + Text(l.pngBlurTap), + Wrap( + spacing: 6, + children: [ + for (final first in [true, false]) + ChoiceChip( + label: Text(first ? l.pngBlurFrom : l.pngBlurTo), + selected: first == start, + onSelected: (_) => setState(() => start = first), + ), + ], + ), + _map(blur, anchor), + _slider(l.pngBlurX, anchor.x, (v) => anchor.x = v), + _slider(l.pngBlurY, anchor.y, (v) => anchor.y = v), + if (!blur.valid) + Text( + l.pngBlurDistinct, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + if (blur.mode != PngBlurMode.off) + _slider( + l.pngBlurStrength, + blur.mode == PngBlurMode.uniform ? blur.uniform : anchor.sigma, + (v) { + if (blur.mode == PngBlurMode.uniform) { + blur.uniform = v; + } else { + anchor.sigma = v; + } + }, + strength: true, + ), + if (blur.active) + Text(l.pngBlurFineHint, style: Theme.of(context).textTheme.bodySmall), + ], + ); + } + + Widget _slider( + String label, + double value, + ValueChanged change, { + bool strength = false, + }) { + String format(double v) => + strength ? '${v.toStringAsFixed(1)} px' : '${(v * 100).round()}%'; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + '$label · ${format(value)}', + style: Theme.of(context).textTheme.labelLarge, + ), + Semantics( + label: label, + child: Slider( + value: value, + max: strength ? 2 : 1, + divisions: strength ? 20 : 100, + label: format(value), + semanticFormatterCallback: format, + onChanged: widget.fields.edited(change), + ), + ), + ], + ); + } + + Widget _map(PngBlur blur, BlurAnchor active) { + final colors = Theme.of(context).colorScheme; + final photo = widget.background; + final values = widget.fields.settings.values; + final width = double.tryParse(values['width'] ?? '') ?? 1; + final height = double.tryParse(values['height'] ?? '') ?? 1; + final paper = photo != null + ? Image.memory(photo.bytes, fit: BoxFit.contain) + : AspectRatio( + aspectRatio: width > 0 && height > 0 && (width / height).isFinite + ? width / height + : .75, + child: ColoredBox(color: colors.surface), + ); + return Container( + height: 142, + color: colors.surfaceContainerLow, + alignment: Alignment.center, + padding: const EdgeInsets.all(8), + child: Stack( + alignment: Alignment.center, + children: [ + paper, + Positioned.fill( + child: LayoutBuilder( + builder: (_, surface) { + return GestureDetector( + key: const ValueKey('png-blur-page'), + behavior: HitTestBehavior.opaque, + onTapDown: widget.fields.locked + ? null + : (event) { + double percent(double position, double span) => + (100 * position / span).round().clamp(0, 100) / + 100; + active.x = percent( + event.localPosition.dx, + surface.maxWidth, + ); + active.y = percent( + event.localPosition.dy, + surface.maxHeight, + ); + widget.fields.onEdited(); + }, + child: CustomPaint( + painter: _AnchorPainter( + Offset(blur.from.x, blur.from.y), + Offset(blur.to.x, blur.to.y), + start, + colors, + ), + ), + ); + }, + ), + ), + ], + ), + ); + } +} + +class _AnchorPainter extends CustomPainter { + const _AnchorPainter(this.from, this.to, this.start, this.colors); + final Offset from, to; + final bool start; + final ColorScheme colors; + + @override + void paint(Canvas canvas, Size size) { + Offset position(Offset p) => Offset(p.dx * size.width, p.dy * size.height); + final a = position(from), b = position(to); + final paint = Paint() + ..color = colors.primary + ..strokeWidth = 2; + canvas.drawLine(a, b, paint); + void mark(Offset point, String label, bool selected) { + final r = math.min(9.0, size.shortestSide / 2); + final center = Offset( + point.dx.clamp(r, size.width - r), + point.dy.clamp(r, size.height - r), + ); + paint.color = selected ? colors.primary : colors.secondaryContainer; + canvas.drawCircle(center, r, paint); + final text = TextPainter( + text: TextSpan( + text: label, + style: TextStyle( + fontSize: r * 1.4, + color: selected ? colors.onPrimary : colors.onSecondaryContainer, + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + text.paint(canvas, center - Offset(text.width / 2, text.height / 2)); + } + + mark(a, 'A', start); + mark(b, 'B', !start); + } + + @override + bool shouldRepaint(_AnchorPainter old) => + old.from != from || + old.to != to || + old.start != start || + old.colors != colors; +} diff --git a/app/lib/widgets/workbench_settings.dart b/app/lib/widgets/workbench_settings.dart index cdb8ac0c..40c5f425 100644 --- a/app/lib/widgets/workbench_settings.dart +++ b/app/lib/widgets/workbench_settings.dart @@ -62,6 +62,7 @@ class WorkbenchSettings extends StatelessWidget { this.activeSection, this.onSectionChanged, this.inkControls, + this.supportsPngBlur = false, }); final Settings settings; final List fonts; @@ -86,6 +87,7 @@ class WorkbenchSettings extends StatelessWidget { final SettingsSection? activeSection; final ValueChanged? onSectionChanged; final Widget? inkControls; + final bool supportsPngBlur; @override Widget build(BuildContext context) { @@ -156,6 +158,7 @@ class WorkbenchSettings extends StatelessWidget { l, fields, background: background, + supportsPngBlur: supportsPngBlur, onUploadBackground: onUploadBackground, onRemoveBackground: onRemoveBackground, onDetectBackground: onDetectBackground, diff --git a/app/test/fine_preview_test.dart b/app/test/fine_preview_test.dart index 7ead716d..3386a58d 100644 --- a/app/test/fine_preview_test.dart +++ b/app/test/fine_preview_test.dart @@ -4,20 +4,24 @@ import 'dart:ui' as ui; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -import 'package:handwriting_app/widgets/workbench_motion.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart' show StandardMessageCodec; import 'package:flutter_test/flutter_test.dart'; import 'package:handwriting_app/l10n/app_localizations.dart'; import 'package:handwriting_app/main.dart'; import 'package:handwriting_app/models/fine_edit.dart'; import 'package:handwriting_app/models/fine_transform.dart'; import 'package:handwriting_app/models/ink_page.dart'; +import 'package:handwriting_app/models/png_blur.dart'; import 'package:handwriting_app/services/api.dart'; import 'package:handwriting_app/services/workspace.dart'; import 'package:handwriting_app/utils/ink_effects.dart' show decodeInkImage; import 'package:handwriting_app/utils/fine_raster.dart'; import 'package:handwriting_app/view_models/fine_selection.dart'; import 'package:handwriting_app/widgets/fine_preview.dart'; +import 'package:handwriting_app/widgets/workbench_motion.dart'; + +import 'workspace_test.dart' show ControlledApi; Future _png(Color background, List ink, Color color) async { final recorder = ui.PictureRecorder(); @@ -55,6 +59,82 @@ Future _page() async => InkPage( ); void main() { + testWidgets('PDF still exports fine edits with invalid PNG gradient', ( + tester, + ) async { + tester.view.physicalSize = const Size(1100, 850); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final api = ControlledApi() + ..supportsFineEdit = true + ..supportsPngBlur = true; + api.submission.complete('pdf'); + final workspace = Workspace(api: api) + ..initialized = true + ..text = 'AB' + ..fonts = ['test.ttf'] + ..fineEnabled = true; + workspace.settings.font = workspace.fonts.single; + final page = (await tester.runAsync(_page))!; + workspace.generation + ..pages = [page.paper] + ..inkPages = [page] + ..previewRevision = workspace.editRevision; + workspace.applyFineEdits(page.fine!, [ + ( + id: 1, + dx: 3, + dy: 0, + scale: 100, + angle: 0, + opacity: 100, + thickness: 0, + softness: 0, + color: null, + warp: null, + ), + ]); + // A softened PNG preview has no editable ink layers. + workspace.generation.inkPages = []; + final blur = workspace.settings.pngBlur; + blur.mode = PngBlurMode.gradient; + blur.to.y = blur.from.y; + workspace.edit(); + addTearDown(workspace.dispose); + + var saves = 0; + tester.binding.defaultBinaryMessenger.setMockMessageHandler( + 'dev.flutter.pigeon.file_saver.FileSaverHostApi.saveAs', + (_) async { + saves++; + return const StandardMessageCodec().encodeMessage(['test.pdf']); + }, + ); + await tester.pumpWidget( + HandwritingApp(locale: const Locale('en'), workspace: workspace), + ); + await tester.pump(); + expect(workspace.previewStale, isTrue); + expect(blur.valid, isFalse); + await tester.tap(find.byKey(const ValueKey('export-pdf'))); + await tester.pumpAndSettle(); + await tester.pump(const Duration(milliseconds: 500)); + + expect(api.previewRequested.isCompleted, isFalse); + final request = api.submittedFields!; + expect(request['pdf_save'], 'true'); + expect(request['preview'], 'false'); + expect(request, isNot(contains('export_blur_gradient'))); + final edits = jsonDecode(request['fine_edits']!) as Map; + expect(edits['key'], page.fine!.key); + expect((edits['glyphs'] as List).single['dx'], 3); + expect(saves, 1); + expect(workspace.exportExtension, 'pdf'); + expect(workspace.error, isEmpty); + expect(blur.valid, isFalse); + }); + testWidgets( 'saving a fine page preserves transparent paper and translucent ink', (tester) async { diff --git a/app/test/png_blur_settings_test.dart b/app/test/png_blur_settings_test.dart new file mode 100644 index 00000000..7e5c0caa --- /dev/null +++ b/app/test/png_blur_settings_test.dart @@ -0,0 +1,105 @@ +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/models/png_blur.dart'; +import 'package:handwriting_app/models/settings.dart'; +import 'package:handwriting_app/widgets/settings/png_blur_settings.dart'; +import 'package:handwriting_app/widgets/settings/settings_fields.dart'; + +void main() { + test('all PNG finishes use the same handwriting for preview and ZIP', () { + final settings = Settings.notebook(); + for (final mode in PngBlurMode.values) { + settings.pngBlur.mode = mode; + for (final preview in [true, false]) { + final fields = settings.form('例 7', preview: preview, pdf: false); + expect(fields['seed'], '0', reason: '$mode, preview=$preview'); + } + } + final legacy = settings.form( + '例 7', + preview: true, + pdf: false, + supportsPngBlur: false, + ); + expect(legacy.containsKey('seed'), isFalse); + expect(legacy.containsKey('export_blur_gradient'), isFalse); + expect( + settings.form('例 7', preview: false, pdf: true).containsKey('seed'), + isFalse, + ); + }); + + testWidgets( + 'paper controls set independent anchors for PNG preview and export', + (tester) async { + final settings = Settings.notebook(); + Map form({bool pdf = false, bool preview = true}) => + settings.form('Example', preview: preview, pdf: pdf); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: Scaffold( + body: SingleChildScrollView( + child: StatefulBuilder( + builder: (_, change) => PngBlurSettings( + fields: SettingsFields( + settings, + 0, + false, + () => change(() {}), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(form().containsKey('export_blur_px'), isFalse); + await tester.tap(find.text('Uniform')); + await tester.pumpAndSettle(); + expect(form()['export_blur_px'], '0.6'); + await tester.tap(find.text('Two-point gradient')); + await tester.pumpAndSettle(); + final map = find.byKey(const ValueKey('png-blur-page')); + await tester.tap(map); + await tester.pump(); + expect(settings.pngBlur.from.y, .5); + await tester.tap(find.text('End B')); + await tester.pumpAndSettle(); + await tester.tap(map); + await tester.pump(); + expect( + find.text('Choose different start and end positions.'), + findsOneWidget, + ); + final box = tester.getRect(map); + await tester.tapAt( + box.topLeft + Offset(.75 * box.width, .8 * box.height), + ); + await tester.pump(); + final fields = form(); + expect(fields.containsKey('export_blur_px'), isFalse); + expect(jsonDecode(fields['export_blur_gradient']!), { + 'from': {'x': .5, 'y': .5, 'sigma_px': 1.2}, + 'to': {'x': .75, 'y': .8, 'sigma_px': 0.0}, + }); + expect( + form(preview: false)['export_blur_gradient'], + fields['export_blur_gradient'], + ); + expect( + form(pdf: true, preview: false).containsKey('export_blur_gradient'), + isFalse, + ); + final restored = Settings()..restore(settings.toJson()); + expect(restored.pngBlur.fields, settings.pngBlur.fields); + expect(tester.takeException(), isNull); + }, + ); +} diff --git a/assets/examples/angled-sheet-5ad065421e7c.webp b/assets/examples/angled-sheet-5ad065421e7c.webp new file mode 100644 index 00000000..4ef58b1d Binary files /dev/null and b/assets/examples/angled-sheet-5ad065421e7c.webp differ diff --git a/assets/examples/flower-shadow-a07835481c3a.webp b/assets/examples/flower-shadow-a07835481c3a.webp new file mode 100644 index 00000000..af89a794 Binary files /dev/null and b/assets/examples/flower-shadow-a07835481c3a.webp differ diff --git a/crates/handwriting-bridge/src/api.rs b/crates/handwriting-bridge/src/api.rs index 8b4769d8..2d31fe5f 100644 --- a/crates/handwriting-bridge/src/api.rs +++ b/crates/handwriting-bridge/src/api.rs @@ -154,7 +154,7 @@ pub fn execute(mut request: Request) -> Result { include_str!("../../handwriting-core/licenses/handright-LICENSE.txt") ))), "version" => Ok( - json!({"version": handwriting_core::app_version(), "capabilities": {"fine_edit": true}}), + json!({"version": handwriting_core::app_version(), "capabilities": {"export_blur": true, "fine_edit": true}}), ), "import" | "identify" | "pdf_page" => { let _operation = OPERATIONS diff --git a/crates/handwriting-bridge/src/api/worker.rs b/crates/handwriting-bridge/src/api/worker.rs index b6935825..d2abc86b 100644 --- a/crates/handwriting-bridge/src/api/worker.rs +++ b/crates/handwriting-bridge/src/api/worker.rs @@ -108,7 +108,7 @@ fn generate(request: Request, task: &Mutex) -> Result<()> { }; let result = if params.pdf_save || !params.preview { Some(export(&render_request, &directory, &cancel, progress)?) - } else if params.ink_layers { + } else if params.preview_ink_layers() { generation::generate( &render_request, &cancel, @@ -136,7 +136,7 @@ fn generate(request: Request, task: &Mutex) -> Result<()> { state.result = Some(path); state.content_type = mime.into(); } else { - state.content_type = if params.ink_layers { + state.content_type = if params.preview_ink_layers() { "application/json" } else { "image/png" diff --git a/crates/handwriting-core/src/export_blur.rs b/crates/handwriting-core/src/export_blur.rs new file mode 100644 index 00000000..add0cba9 --- /dev/null +++ b/crates/handwriting-core/src/export_blur.rs @@ -0,0 +1,488 @@ +use crate::{Cancellation, Error, Result}; +use image::{Rgba, RgbaImage}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[cfg_attr(feature = "local-fonts", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields)] +pub struct Anchor { + /// Horizontal position in the full image, 0 at the leftmost pixel and 1 at the rightmost. + #[cfg_attr(feature = "local-fonts", schemars(range(min = 0, max = 1)))] + pub x: f64, + /// Vertical position in the full image, 0 at the top pixel and 1 at the bottom. + #[cfg_attr(feature = "local-fonts", schemars(range(min = 0, max = 1)))] + pub y: f64, + /// Gaussian sigma in original image pixels. + #[cfg_attr(feature = "local-fonts", schemars(range(min = 0, max = 2)))] + pub sigma_px: f64, +} + +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[cfg_attr(feature = "local-fonts", derive(schemars::JsonSchema))] +#[serde(deny_unknown_fields)] +pub struct Gradient { + /// The starting position and blur strength. + pub from: Anchor, + /// The distinct end position and blur strength. Outside the segment the nearest end strength applies. + pub to: Anchor, +} + +impl Gradient { + fn validate(self) -> Result<()> { + for anchor in [self.from, self.to] { + if !(0.0..=1.0).contains(&anchor.x) + || !(0.0..=1.0).contains(&anchor.y) + || !(0.0..=2.0).contains(&anchor.sigma_px) + { + return Err(Error::new( + "invalid_parameter", + "export_blur_gradient requires x and y from 0 to 1, and sigma_px from 0 to 2 original image pixels.", + )); + } + } + if self.from.x == self.to.x && self.from.y == self.to.y { + return Err(Error::new( + "invalid_parameter", + "export_blur_gradient needs two distinct anchor positions.", + )); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug)] +pub enum Finish { + Uniform(f64), + Gradient(Gradient), +} + +pub fn finish(uniform: Option, gradient: Option) -> Result> { + match (uniform, gradient) { + (None, None) => Ok(None), + (Some(_), Some(_)) => Err(Error::new( + "invalid_parameter", + "Supply only one of export_blur_px and export_blur_gradient, even when the uniform value is 0.", + )), + (Some(sigma), None) => { + validate(sigma)?; + Ok(Some(Finish::Uniform(sigma))) + } + (None, Some(g)) => { + g.validate()?; + Ok(Some(Finish::Gradient(g))) + } + } +} + +impl Finish { + pub fn active(self) -> bool { + match self { + Self::Uniform(sigma) => sigma > 0., + Self::Gradient(g) => g.from.sigma_px > 0. || g.to.sigma_px > 0., + } + } + + pub fn write_metadata(self, object: &mut Value) { + match self { + Self::Uniform(sigma) => object["export_blur_px"] = json!(sigma), + Self::Gradient(g) => object["export_blur_gradient"] = json!(g), + } + } + + pub fn apply(self, page: &RgbaImage, cancel: &Cancellation) -> Result { + match self { + Self::Uniform(sigma) => apply(page, sigma, cancel), + Self::Gradient(g) => apply_gradient(page, g, cancel), + } + } +} + +pub fn validate(sigma: f64) -> Result<()> { + if (0.0..=2.0).contains(&sigma) { + Ok(()) + } else { + Err(Error::new( + "invalid_parameter", + "export_blur_px must be a Gaussian sigma from 0 to 2 original image pixels.", + )) + } +} + +// 最大 sigma 为 2,三倍标准差截断的核每侧最多六个像素。 +struct Kernel { + weights: [f32; 13], + radius: usize, +} + +impl Kernel { + fn new(sigma: f64) -> Self { + let radius = (3. * sigma).ceil() as usize; + let mut weights = [0.; 13]; + weights[radius] = 1.; + for i in 1..=radius { + let value = (-0.5 * (i as f64 / sigma).powi(2)).exp() as f32; + weights[radius - i] = value; + weights[radius + i] = value; + } + let taps = &mut weights[..=2 * radius]; + let sum: f32 = taps.iter().sum(); + for weight in taps { + *weight /= sum; + } + Self { weights, radius } + } + + fn taps(&self) -> &[f32] { + &self.weights[..=2 * self.radius] + } + + fn horizontal(&self, page: &RgbaImage, x: usize, y: usize) -> [f32; 4] { + let mut total = [0.; 4]; + let w = page.width() as usize; + for (k, &weight) in self.taps().iter().enumerate() { + let sample_x = x + .saturating_add_signed(k as isize - self.radius as isize) + .min(w - 1); + let [r, g, b, a] = page[(sample_x as u32, y as u32)].0; + let weighted_alpha = f32::from(a) * weight; + total[0] += weighted_alpha * f32::from(r); + total[1] += weighted_alpha * f32::from(g); + total[2] += weighted_alpha * f32::from(b); + total[3] += weighted_alpha; + } + total + } +} + +fn straight_rgba(total: [f32; 4]) -> Rgba { + let alpha = total[3].round() as u8; + let rgb = |c: f32| { + if alpha == 0 { + 0 + } else { + (c / total[3]).round() as u8 + } + }; + Rgba([rgb(total[0]), rgb(total[1]), rgb(total[2]), alpha]) +} + +fn apply_gradient(page: &RgbaImage, g: Gradient, cancel: &Cancellation) -> Result { + g.validate()?; + cancel.check()?; + if g.from.sigma_px == g.to.sigma_px { + return apply(page, g.from.sigma_px, cancel); + } + let (w, h) = page.dimensions(); + if w == 0 || h == 0 { + return Ok(page.clone()); + } + let (from, to) = if (g.from.x, g.from.y) <= (g.to.x, g.to.y) { + (g.from, g.to) + } else { + (g.to, g.from) + }; + let (wx, hy) = (f64::from(w - 1), f64::from(h - 1)); + let (sx, sy) = (from.x * wx, from.y * hy); + let (dx, dy) = (to.x * wx - sx, to.y * hy - sy); + let span = dx.abs().max(dy.abs()); + if span == 0. { + return apply(page, from.sigma_px.midpoint(to.sigma_px), cancel); + } + // 缩放同一投影的分子和分母,避免极近锚点的距离平方下溢。 + let (ux, uy) = (dx / span, dy / span); + let length = dx * ux + dy * uy; + let first = Kernel::new(from.sigma_px); + let last = Kernel::new(to.sigma_px); + let mut out = RgbaImage::new(w, h); + for (y, row) in out.rows_mut().enumerate() { + let y_dot = (y as f64 - sy) * uy; + for (x, pixel) in row.enumerate() { + if x % 512 == 0 { + cancel.check()?; + } + let t = ((x as f64 - sx) * ux + y_dot) / length; + let middle; + let kernel = if t <= 0. { + &first + } else if t >= 1. { + &last + } else { + middle = Kernel::new((1. - t) * from.sigma_px + t * to.sigma_px); + &middle + }; + if kernel.radius == 0 { + *pixel = page[(x as u32, y as u32)]; + continue; + } + // 两轴都取输出点的 sigma;先按输入行位置套一次渐变会使斜向边界偏色。 + let mut total = [0.; 4]; + for (k, &weight) in kernel.taps().iter().enumerate() { + let sample_y = y + .saturating_add_signed(k as isize - kernel.radius as isize) + .min(h as usize - 1); + for (v, sample) in total.iter_mut().zip(kernel.horizontal(page, x, sample_y)) { + *v += weight * sample; + } + } + *pixel = straight_rgba(total); + } + } + Ok(out) +} + +/// Filter the completed native-resolution page, including paper and alpha, in its stored RGB space. +pub fn apply(page: &RgbaImage, sigma: f64, cancel: &Cancellation) -> Result { + validate(sigma)?; + cancel.check()?; + if sigma == 0. || page.width() == 0 || page.height() == 0 { + return Ok(page.clone()); + } + let filter = Kernel::new(sigma); + let radius = filter.radius as isize; + let kernel = filter.taps(); + let (w, h) = (page.width() as usize, page.height() as usize); + let mut out = RgbaImage::new(page.width(), page.height()); + // 2026-11-27:分带只缓存双向高斯卷积所需的几行;透明像素的隐藏 RGB 不参与混色。 + for left in (0..w).step_by(512) { + let width = (w - left).min(512); + let mut rows = vec![vec![[0f32; 4]; width]; kernel.len().min(h)]; + let slots = rows.len(); + let mut next = 0; + for y in 0..h { + if y % 32 == 0 { + cancel.check()?; + } + while next <= (y + radius as usize).min(h - 1) { + let row = &mut rows[next % slots]; + for (col, filtered) in row.iter_mut().enumerate() { + *filtered = filter.horizontal(page, left + col, next); + } + next += 1; + } + for col in 0..width { + let mut total = [0.; 4]; + for (k, &weight) in kernel.iter().enumerate() { + let sample_y = y.saturating_add_signed(k as isize - radius).min(h - 1); + for (v, sample) in total.iter_mut().zip(rows[sample_y % slots][col]) { + *v += weight * sample; + } + } + out[((left + col) as u32, y as u32)] = straight_rgba(total); + } + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn anchor(x: f64, y: f64, sigma_px: f64) -> Anchor { + Anchor { x, y, sigma_px } + } + + // Independent 2-D Gaussian reference; accumulate premultiplied channels in double precision. + fn reference(page: &RgbaImage, x: u32, y: u32, sigma: f64) -> [u8; 4] { + if sigma == 0. { + return page[(x, y)].0; + } + let radius = (3. * sigma).ceil() as i32; + let mut total = [0.; 4]; + let mut norm = 0.; + for dy in -radius..=radius { + for dx in -radius..=radius { + let weight = (-f64::from(dx * dx + dy * dy) / (2. * sigma * sigma)).exp(); + let px = x.saturating_add_signed(dx).min(page.width() - 1); + let py = y.saturating_add_signed(dy).min(page.height() - 1); + let p = page[(px, py)].0.map(f64::from); + for c in 0..3 { + total[c] += weight * p[3] * p[c]; + } + total[3] += weight * p[3]; + norm += weight; + } + } + let alpha = (total[3] / norm).round() as u8; + if alpha == 0 { + [0; 4] + } else { + [0, 1, 2, 3].map(|i| { + if i == 3 { + alpha + } else { + (total[i] / total[3]).round() as u8 + } + }) + } + } + + #[test] + fn directional_rgba_matches_output_point_gaussians_in_native_pixel_geometry() { + let page = RgbaImage::from_fn(33, 17, |x, y| { + Rgba([ + ((29 * x + 19 * y) % 256) as u8, + ((13 * x + 37 * y) % 256) as u8, + 191, + if x <= 5 { + 0 + } else { + ((47 * x + 11 * y) % 256) as u8 + }, + ]) + }); + let cancel = Cancellation::default(); + let full = apply(&page, 1.78, &cancel).unwrap(); + for (from, to, vector) in [ + (anchor(0.125, 0.25, 0.), anchor(0.875, 0.25, 1.78), [24, 0]), + (anchor(0.125, 0.25, 0.), anchor(0.125, 0.75, 1.78), [0, 8]), + (anchor(0.125, 0.25, 0.), anchor(0.875, 0.75, 1.78), [24, 8]), + ] { + let result = Finish::Gradient(Gradient { from, to }) + .apply(&page, &cancel) + .unwrap(); + let reverse = Finish::Gradient(Gradient { from: to, to: from }) + .apply(&page, &cancel) + .unwrap(); + assert_eq!(result, reverse); + let [dx, dy] = vector.map(f64::from); + for (x, y, pixel) in result.enumerate_pixels() { + let t = (((f64::from(x) - 4.) * dx + (f64::from(y) - 4.) * dy) + / (dx * dx + dy * dy)) + .clamp(0., 1.); + if t == 0. { + assert_eq!(*pixel, page[(x, y)]); + } + if t == 1. { + assert_eq!(*pixel, full[(x, y)]); + } + let expected = reference(&page, x, y, t * 1.78); + assert!( + pixel + .0 + .iter() + .zip(expected) + .all(|(a, b)| a.abs_diff(b) <= 1), + "({x},{y}) t={t}: {pixel:?} vs {expected:?}" + ); + } + } + } + + #[test] + fn equal_sigmas_collapsed_dimensions_and_nearly_coincident_anchors() { + let page = RgbaImage::from_fn(19, 1, |x, _| { + Rgba([90, x as u8, 219, if x % 2 == 0 { 0 } else { 255 }]) + }); + let cancel = Cancellation::default(); + for sigma in [0., 0.6, 2.] { + let flat = Finish::Gradient(Gradient { + from: anchor(0., 0., sigma), + to: anchor(1., 1., sigma), + }); + assert_eq!(flat.active(), sigma > 0.); + assert_eq!( + flat.apply(&page, &cancel).unwrap(), + apply(&page, sigma, &cancel).unwrap() + ); + } + let collapsed = Finish::Gradient(Gradient { + from: anchor(0., 0., 0.), + to: anchor(0., 1., 2.), + }); + assert_eq!( + collapsed.apply(&page, &cancel).unwrap(), + apply(&page, 1., &cancel).unwrap() + ); + let tiny = Finish::Gradient(Gradient { + from: anchor(0., 0., 0.), + to: anchor(f64::from_bits(1), 0., 2.), + }); + let result = tiny.apply(&page, &cancel).unwrap(); + let full = apply(&page, 2., &cancel).unwrap(); + for x in 0..page.width() { + assert_eq!( + result[(x, 0)], + if x == 0 { page[(0, 0)] } else { full[(x, 0)] } + ); + } + let solid = RgbaImage::from_pixel(3, 7, Rgba([40, 66, 253, 97])); + assert_eq!(tiny.apply(&solid, &cancel).unwrap(), solid); + cancel.cancel(); + assert!(tiny.apply(&solid, &cancel).is_err()); + } + + #[test] + fn validates_range_exclusivity_and_retains_requested_anchor_order_in_metadata() { + let g = Gradient { + from: anchor(1., 0.8, 1.5), + to: anchor(0.1, 0., 0.), + }; + assert!(finish(None, None).unwrap().is_none()); + assert!(finish(Some(0.), Some(g)).is_err()); + assert!(!finish(Some(0.), None).unwrap().unwrap().active()); + for bad in [ + anchor(f64::NAN, 0., 1.), + anchor(1., 1.001, 1.), + anchor(0., 0., 2.1), + g.to, + ] { + assert!( + finish( + None, + Some(Gradient { + from: bad, + to: g.to + }) + ) + .is_err() + ); + } + let mut metadata = json!({"revision":7}); + finish(None, Some(g)) + .unwrap() + .unwrap() + .write_metadata(&mut metadata); + assert_eq!( + metadata, + json!({"revision":7,"export_blur_gradient":{"from":{"x":1.,"y":0.8,"sigma_px":1.5},"to":{"x":0.1,"y":0.,"sigma_px":0.}}}) + ); + } + + #[test] + fn gaussian_crosses_band_boundaries_without_mixing_hidden_colors() { + let mut page = RgbaImage::from_pixel(515, 9, Rgba([1, 250, 18, 0])); + page[(511, 4)] = Rgba([207, 13, 99, 255]); + let result = apply(&page, 1., &Cancellation::default()).unwrap(); + assert_eq!(result.dimensions(), page.dimensions()); + // A unit impulse convolved by the normalized 2-D Gaussian, sigma=1. + for (x, y, a) in [ + (511, 4, 41), + (510, 4, 25), + (512, 4, 25), + (511, 3, 25), + (512, 5, 15), + ] { + assert_eq!(result[(x, y)].0, [207, 13, 99, a]); + } + assert_eq!(result[(5, 4)].0, [0; 4]); + assert_eq!(apply(&page, 0., &Cancellation::default()).unwrap(), page); + } + + #[test] + fn maximum_radius_preserves_uniform_tiny_pages_and_responds_to_cancellation() { + let page = RgbaImage::from_pixel(2, 1, Rgba([31, 62, 93, 127])); + assert_eq!(apply(&page, 2., &Cancellation::default()).unwrap(), page); + assert_eq!( + apply(&page, f64::MIN_POSITIVE, &Cancellation::default()).unwrap(), + page + ); + let cancel = Cancellation::default(); + cancel.cancel(); + assert!(apply(&page, 1., &cancel).is_err()); + for v in [-0.01, 2.01, f64::NAN, f64::INFINITY] { + assert!(validate(v).is_err()); + } + } +} diff --git a/crates/handwriting-core/src/fine_edit.rs b/crates/handwriting-core/src/fine_edit.rs index fc7b9381..e89a9795 100644 --- a/crates/handwriting-core/src/fine_edit.rs +++ b/crates/handwriting-core/src/fine_edit.rs @@ -15,6 +15,9 @@ pub struct Adjustment { pub scale: u8, pub angle: i8, pub opacity: u8, + // 2026-11-27:以未变换图块高度为坐标,在两个锚点间渐变笔迹浓度。 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub opacity_ramp: Option, pub color: Option<[u8; 3]>, // 2026-11-18:相对全局设置的偏移,以 0.1 px 为单位。 #[serde(default)] @@ -25,6 +28,31 @@ pub struct Adjustment { pub warp: Option<[f64; 8]>, } +#[derive(Clone, Copy, Debug, Deserialize, Serialize)] +#[serde(transparent)] +pub struct OpacityRamp(pub [[u8; 2]; 2]); + +impl OpacityRamp { + pub fn valid(self) -> bool { + self.0[0][0] < self.0[1][0] && self.0.into_iter().flatten().all(|v| v <= 100) + } + + fn multiplier(self, position: f64) -> f64 { + let [[start, a], [end, b]] = self.0.map(|pair| pair.map(f64::from)); + let t = ((position - start) / (end - start)).clamp(0., 1.); + (a + t * (b - a)) / 100. + } +} + +impl Adjustment { + pub fn hides_ink(&self) -> bool { + self.opacity == 0 + || self + .opacity_ramp + .is_some_and(|ramp| ramp.0.iter().all(|point| point[1] == 0)) + } +} + #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct Adjustments { @@ -37,6 +65,8 @@ pub struct Adjustments { pub struct GlyphBounds { #[serde(skip)] pub is_text: bool, + #[serde(skip)] + pub is_native_diagram: bool, pub illustration: Option, pub id: u32, pub bounds: [i32; 4], @@ -64,6 +94,7 @@ pub fn inspect_page( .map(|t| GlyphBounds { id: t.id, is_text: t.is_text, + is_native_diagram: t.is_native_diagram, illustration: t.illustration, bounds: [t.x, t.y, t.mask.width() as i32, t.mask.height() as i32], source_utf16: t.source, @@ -109,6 +140,7 @@ impl Adjustments { && (50..=200).contains(&v.scale) && (-45..=45).contains(&v.angle) && v.opacity <= 100 + && v.opacity_ramp.is_none_or(OpacityRamp::valid) && (-20..=20).contains(&v.thickness) && (-20..=20).contains(&v.softness) && v.warp @@ -131,6 +163,7 @@ pub(crate) fn document_key(text: &str, p: &Parameters) -> String { pub(crate) struct Tile { pub is_text: bool, + pub is_native_diagram: bool, pub illustration: Option, pub id: u32, pub x: i32, @@ -293,11 +326,12 @@ pub(crate) fn paint( edit: Option<&Adjustment>, cancel: &Cancellation, ) -> Result<()> { - let (base_thickness, base_softness, base_fill, base_opacity) = if tile.illustration.is_some() { - (0., 0., [20, 20, 25, 255], 100) - } else { - (p.ink_thickness, p.ink_softness, p.fill, p.ink_opacity) - }; + let (base_thickness, base_softness, base_fill, base_opacity) = + if tile.illustration.is_some() && !p.illustration_uses_pen { + (0., 0., [20, 20, 25, 255], 100) + } else { + (p.ink_thickness, p.ink_softness, p.fill, p.ink_opacity) + }; let thickness = (base_thickness + edit.map_or(0., |v| f64::from(v.thickness) / 10.)).clamp(-2., 2.); let softness = (base_softness + edit.map_or(0., |v| f64::from(v.softness) / 10.)).clamp(0., 2.); @@ -318,6 +352,14 @@ pub(crate) fn paint( .and_then(|v| v.color) .unwrap_or([base_fill[0], base_fill[1], base_fill[2]]); let opacity = u32::from(edit.map_or(100, |v| v.opacity)); + let row_opacity = edit.and_then(|e| e.opacity_ramp).map(|ramp| { + (0..mask.height()) + .map(|y| { + let position = (f64::from(y) + 0.5) * 100. / h; + (f64::from(opacity) * ramp.multiplier(position)).round() as u32 + }) + .collect::>() + }); for y in ((cy + top).floor().max(0.) as u32) ..((cy + bottom).ceil().max(0.) as u32).min(paper.height()) { @@ -343,7 +385,10 @@ pub(crate) fn paint( * u32::from(base_fill[3]) + 12_750) / 25_500; - let alpha = (alpha * opacity + 50) / 100; + let local = row_opacity + .as_ref() + .map_or(opacity, |rows| rows[sy as usize]); + let alpha = (alpha * local + 50) / 100; let pixel = &mut paper[(x, y)]; if pixel[3] < 255 { use image::Pixel; @@ -375,6 +420,7 @@ mod tests { scale: 100, angle: 0, opacity: 100, + opacity_ramp: None, color: None, thickness: 0, softness: 0, diff --git a/crates/handwriting-core/src/generation.rs b/crates/handwriting-core/src/generation.rs index bffb35f6..8e828ba7 100644 --- a/crates/handwriting-core/src/generation.rs +++ b/crates/handwriting-core/src/generation.rs @@ -47,11 +47,15 @@ pub fn generate( cancel.check()?; let camera = export::CameraMetadata::from_paper(request.background.as_deref(), &request.params.camera)?; + let finish_png = |image: image::RgbaImage| match request.params.png_finish { + Some(finish) if finish.active() => finish.apply(&image, cancel), + _ => Ok(image), + }; match output { Output::Preview(emit) => { render::render(request, cancel, |index, image| { cancel.check()?; - let bytes = camera.png(&image)?; + let bytes = camera.png(&finish_png(image)?)?; cancel.check()?; emit(index, bytes)?; progress(Event::PageReady(index + 1))?; @@ -121,7 +125,7 @@ pub fn generate( let mut zip = export::ZipExport::new(writer); render::render(request, cancel, |index, image| { cancel.check()?; - zip.add_with_camera(index, &image, &camera)?; + zip.add_with_camera(index, &finish_png(image)?, &camera)?; progress(Event::PageReady(index + 1))?; cancel.check() })?; diff --git a/crates/handwriting-core/src/lib.rs b/crates/handwriting-core/src/lib.rs index a1cbed81..7c348983 100644 --- a/crates/handwriting-core/src/lib.rs +++ b/crates/handwriting-core/src/lib.rs @@ -1,6 +1,7 @@ //! 跨平台生成核心;2026-10-12:不依赖 HTTP、Flutter 或全局工作目录。 pub mod document; pub mod export; +pub mod export_blur; pub mod fine_edit; pub mod fonts; pub mod generation; diff --git a/crates/handwriting-core/src/parameters.rs b/crates/handwriting-core/src/parameters.rs index a3ed0d6b..8eb3e696 100644 --- a/crates/handwriting-core/src/parameters.rs +++ b/crates/handwriting-core/src/parameters.rs @@ -45,6 +45,8 @@ fn default_latin_scale() -> u8 { /// A struct update using `..Parameters::default()` picks up optional export fields. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Parameters { + #[serde(skip)] + pub png_finish: Option, #[serde(flatten)] pub camera: crate::export::CameraInput, #[serde(default)] @@ -82,6 +84,8 @@ pub struct Parameters { pub ink_depth_sigma: f32, pub ink_layers: bool, #[serde(default)] + pub illustration_uses_pen: bool, + #[serde(default)] pub transparent_background: bool, #[serde(default)] pub fine_edit: bool, @@ -105,6 +109,7 @@ pub struct Parameters { impl Default for Parameters { fn default() -> Self { Self { + png_finish: None, camera: Default::default(), layout_style: LayoutStyle::Standard, paper_pattern: None, @@ -133,6 +138,7 @@ impl Default for Parameters { strikethrough_width: 8., ink_depth_sigma: 30., ink_layers: false, + illustration_uses_pen: false, transparent_background: false, fine_edit: false, fine_edits: None, @@ -234,7 +240,19 @@ impl Parameters { p.preview = boolean(f, "preview", true)?; p.full_preview = boolean(f, "full_preview", true)?; p.pdf_save = boolean(f, "pdf_save", false)?; + let uniform = f + .get("export_blur_px") + .map(|v| v.parse()) + .transpose() + .map_err(|_| Error::new("invalid_parameter", "export_blur_px"))?; + let gradient = f + .get("export_blur_gradient") + .map(|v| serde_json::from_str(v)) + .transpose() + .map_err(|_| Error::new("invalid_parameter", "export_blur_gradient"))?; + p.png_finish = crate::export_blur::finish(uniform, gradient)?; p.ink_layers = boolean(f, "ink_layers", false)?; + p.illustration_uses_pen = boolean(f, "illustration_uses_pen", false)?; p.transparent_background = boolean(f, "transparent_background", false)?; p.fine_edit = boolean(f, "fine_edit", false)?; if p.fine_edit { @@ -321,6 +339,10 @@ impl Parameters { } Ok(()) } + pub fn preview_ink_layers(&self) -> bool { + self.ink_layers && !self.png_finish.is_some_and(|f| f.active()) + } + // 2026-10-12:保留 Python 入口对右边距的字距补偿。 pub fn effective_right_margin(&self) -> f32 { self.right_margin - self.word_spacing * 2. diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index 50fba85b..a6b15b41 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -48,6 +48,7 @@ use units::{fixed_cell, keeps_grid_cell, layout_units}; // 2026-10-15:先缓存整行,知道最高根式/最低分母后再统一落笔,避免后出现的公式撞进上一行。 struct LineUnit { is_text: bool, + is_native_diagram: bool, glyph: Glyph, rigid: bool, align_to_rulings: bool, @@ -478,7 +479,7 @@ fn render_planes( (h as f32 - p.top_margin - p.bottom_margin).max(1.) as u32, imaging::scale(alt), ); - let image = imaging::handdrawn( + let mut image = imaging::handdrawn( &image::DynamicImage::ImageRgba8(fitted), p.seed.wrapping_add(i as u64), cancel, @@ -512,6 +513,17 @@ fn render_planes( pages.push_tile(tile)?; } } else { + if p.illustration_uses_pen { + let mask = GrayImage::from_fn(image.width(), image.height(), |x, y| { + image::Luma([image[(x, y)][3]]) + }); + image = ink_effects::composite( + RgbaImage::new(image.width(), image.height()), + mask, + &r.params, + cancel, + )?; + } image::imageops::overlay(&mut pages.canvas, &image, x as i64, top as i64); } pages.dirty = true; @@ -557,6 +569,7 @@ fn render_planes( let advance = g.step(unit, p, extra, compound); pages.x = x + advance; pages.line.push(LineUnit { + is_native_diagram: matches!(node, Node::Circuit(_)), is_text: unit.iter().all(|node| matches!(node, Node::Char(_))), glyph: g, rigid: compound || cell.is_some(), @@ -588,6 +601,7 @@ mod ruled_tests { fn sample_line() -> Vec { vec![LineUnit { is_text: true, + is_native_diagram: false, glyph: Glyph { mask: GrayImage::from_pixel(8, 40, Luma([255])), advance: 8., diff --git a/crates/handwriting-core/src/render/fine.rs b/crates/handwriting-core/src/render/fine.rs index 63a223ef..6294dbb9 100644 --- a/crates/handwriting-core/src/render/fine.rs +++ b/crates/handwriting-core/src/render/fine.rs @@ -178,6 +178,7 @@ fn capture_one( ink::paste_mask(&mut mask, &crop, pad as i32, pad as i32); Ok(Some(fine_edit::Tile { is_text: unit.is_text, + is_native_diagram: unit.is_native_diagram, id: unit.id, illustration: None, x: origin.0 + left as i32 - radius as i32 - pad as i32, diff --git a/crates/handwriting-core/src/render/glyph/circuit.rs b/crates/handwriting-core/src/render/glyph/circuit.rs index 7a861c4f..b45ed03e 100644 --- a/crates/handwriting-core/src/render/glyph/circuit.rs +++ b/crates/handwriting-core/src/render/glyph/circuit.rs @@ -6,6 +6,7 @@ use rand_chacha::ChaCha8Rng; use std::f32::consts::{PI, TAU}; mod branch; +mod flowchart; #[derive(Clone, Copy)] enum Stroke { @@ -17,6 +18,7 @@ type CircuitPath = (Vec<(i32, i32)>, Stroke); struct Drawing { paths: Vec, scale: f32, + arrow_size: f32, naturalness: f32, rng: ChaCha8Rng, holes: Vec, @@ -201,7 +203,7 @@ impl Drawing { if len > 0. { let ux = dx / len; let uy = dy / len; - let back = 0.13_f32.min(len * 0.45); + let back = self.arrow_size.min(len * 0.45); let wing = back * 0.47; self.path(vec![ Point(b.0 - ux * back - uy * wing, b.1 - uy * back + ux * wing), @@ -212,7 +214,7 @@ impl Drawing { } } // 2026-11-22:按字体采样的小数笔宽覆盖像素,避免整数笔刷把两像素线扩成三像素。 -fn pen_paths(paths: Vec, width: f32) -> Result> { +fn pen_paths(paths: Vec, width: f32, pen_offset: f32) -> Result> { let mut points = paths.iter().flat_map(|(points, _)| points); let Some(&(x, y)) = points.next() else { return Ok(None); @@ -230,6 +232,11 @@ fn pen_paths(paths: Vec, width: f32) -> Result> { Stroke::Pen => width, Stroke::DotFill => 1., }; + let offset = if matches!(pen, Stroke::Pen) { + pen_offset + } else { + 0. + }; let reach = (diameter + 1.) * 0.5; for pair in points.windows(2) { let ((ax, ay), (bx, by)) = (pair[0], pair[1]); @@ -237,7 +244,7 @@ fn pen_paths(paths: Vec, width: f32) -> Result> { let length_sq = (dx * dx + dy * dy).max(1.); for y in ay.min(by) - pad..=ay.max(by) + pad { for x in ax.min(bx) - pad..=ax.max(bx) + pad { - let (px, py) = ((x - ax) as f32, (y - ay) as f32); + let (px, py) = ((x - ax) as f32 - offset, (y - ay) as f32 - offset); let t = ((px * dx + py * dy) / length_sq).clamp(0., 1.); let distance = (px - t * dx).hypot(py - t * dy); let alpha = @@ -270,7 +277,18 @@ impl Glyphs<'_> { f32::NEG_INFINITY, f32::NEG_INFINITY, ); - for p in circuit.segments.iter().flat_map(|s| [s.start, s.end]) { + for p in circuit + .segments + .iter() + .flat_map(|s| [s.start, s.end]) + .chain( + circuit + .decorations + .iter() + .filter(|_| circuit.flowchart) + .map(|d| d.point), + ) + { bounds.0 = bounds.0.min(p.0); bounds.1 = bounds.1.min(p.1); bounds.2 = bounds.2.max(p.0); @@ -278,9 +296,20 @@ impl Glyphs<'_> { } let span = (bounds.2 - bounds.0).max(bounds.3 - bounds.1).max(1.); let scale = (size * 1.75).clamp(10., 160.).min(1800. / span); + let standard = self.pen.thickness(size); + let width = if circuit.flowchart { + flowchart::pen_width(self.book.primary(), size, standard) + } else { + standard + }; let mut draw = Drawing { paths: Vec::new(), scale, + arrow_size: if circuit.flowchart { + (width * 4. / scale).max(0.20) + } else { + 0.13 + }, naturalness: self.pen.naturalness, rng: self.next_drawing_rng(), holes: Vec::new(), @@ -291,13 +320,29 @@ impl Glyphs<'_> { .chain(circuit.decorations.iter().map(|d| d.point)) .collect(), }; + let mut children = Vec::new(); + let nodes = if circuit.flowchart { + flowchart::nodes(self, circuit, &draw, size, depth, &mut children)? + } else { + Vec::new() + }; let mut labels: Vec<(String, Point, i32)> = Vec::new(); for segment in &circuit.segments { - branch::draw(&mut draw, segment, circuit.american, &mut labels)?; + if circuit.flowchart && segment.kind == "short" { + let segment = flowchart::clip(segment, &nodes)?; + draw.contacts.extend([segment.start, segment.end]); + branch::draw(&mut draw, &segment, circuit.american, &mut labels)?; + } else { + branch::draw(&mut draw, segment, circuit.american, &mut labels)?; + } + } + for node in &nodes { + node.outline(&mut draw); } for decoration in &circuit.decorations { let p = decoration.point; match decoration.kind.as_str() { + "circle" | "rectangle" | "diamond" => {} "circ" => draw.dot(p, false), "ocirc" => draw.dot(p, true), "ground" => { @@ -341,9 +386,9 @@ impl Glyphs<'_> { } } } - let mut children = Vec::new(); + let label_size = if circuit.flowchart { size } else { size * 0.69 }; for (text, p, anchor) in labels { - let g = self.sequence_at(&crate::text::parse(&text), size * 0.69, depth + 1)?; + let g = self.sequence_at(&crate::text::parse(&text), label_size, depth + 1)?; let (x, y) = draw.point(p); let x = match anchor { -1 => x - g.right(), @@ -353,7 +398,13 @@ impl Glyphs<'_> { let y = y - (g.top + g.bottom()) / 2; children.push((g, x, y)); } - if let Some(ink) = pen_paths(draw.finish(), self.pen.thickness(size))? { + // 刚性墨迹以 128 为阈值,偶数像素笔宽须落在两列/两行之间。 + let offset = if circuit.flowchart && (width.round() as u32).is_multiple_of(2) { + 0.5 + } else { + 0. + }; + if let Some(ink) = pen_paths(draw.finish(), width, offset)? { children.push((ink, 0, 0)); } let mut result = Self::compose(0., children, Vec::new())?; @@ -370,6 +421,7 @@ mod tests { Drawing { paths: Vec::new(), scale, + arrow_size: 0.13, naturalness: 1., rng: rand::SeedableRng::seed_from_u64(20261123), holes: Vec::new(), @@ -402,7 +454,7 @@ mod tests { #[test] fn horizontal_ink_coverage_tracks_fractional_pen_width() { for width in [0.75, 1., 1.4, 2., 2.8] { - let ink = pen_paths(vec![(vec![(0, 0), (20, 0)], Stroke::Pen)], width) + let ink = pen_paths(vec![(vec![(0, 0), (20, 0)], Stroke::Pen)], width, 0.) .unwrap() .unwrap(); let coverage: f32 = (0..ink.mask.height()) @@ -416,7 +468,7 @@ mod tests { fn subpixel_wires_survive_the_page_ink_threshold() { use imageproc::region_labelling::{Connectivity, connected_components}; for end in [(72, 31), (31, -72), (-72, -13), (-17, 72), (72, 0), (0, 72)] { - let wire = pen_paths(vec![(vec![(0, 0), end], Stroke::Pen)], 0.75) + let wire = pen_paths(vec![(vec![(0, 0), end], Stroke::Pen)], 0.75, 0.) .unwrap() .unwrap(); let ink = GrayImage::from_fn(wire.mask.width(), wire.mask.height(), |x, y| { diff --git a/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs b/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs new file mode 100644 index 00000000..b901a021 --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/circuit/flowchart.rs @@ -0,0 +1,305 @@ +//! 2026-11-27:用正文字形定节点边框,以路径的原始中心坐标确定实际箭头接点。 +use super::{Circuit, Drawing, Glyphs, Point, PositionedGlyph, Result, TAU}; +use crate::{Error, text::circuit::Segment}; + +// 取字形前景像素所在的最短横截面;在转折、交叉处用中位数抑制局部膨大。 +pub(super) fn pen_width(font: &fontdue::Font, size: f32, fallback: f32) -> f32 { + let sample_size = size.round().clamp(1., 96.); + let mut widths = Vec::new(); + for c in ['B', 'n', '1', '十', '口'] { + if font.lookup_glyph_index(c) == 0 { + continue; + } + let m = font.metrics(c, sample_size); + if m.width > 192 || m.height > 192 || m.width * m.height > 16_384 { + continue; + } + let (_, pixels) = font.rasterize(c, sample_size); + if let Some(width) = stroke_section(&pixels, m.width, m.height) { + widths.push(width); + } + } + widths.sort_by(f32::total_cmp); + widths + .get(widths.len() / 2) + .map_or(fallback, |w| w * size / sample_size) + .max(1.) +} + +fn stroke_section(pixels: &[u8], width: usize, height: usize) -> Option { + let inside = |x: i32, y: i32| { + x >= 0 + && y >= 0 + && (x as usize) < width + && (y as usize) < height + && pixels[y as usize * width + x as usize] >= 128 + }; + let mut sections = vec![f32::INFINITY; pixels.len()]; + for (dx, dy) in [(1, 0), (0, 1), (1, 1), (1, -1)] { + let step = if dx * dy == 0 { + 1. + } else { + std::f32::consts::SQRT_2 + }; + for (i, &pixel) in pixels.iter().enumerate() { + let (x, y) = ((i % width) as i32, (i / width) as i32); + // 仅在线段起点扫描,使每个方向的总工作量与采样面积成正比。 + if pixel < 128 || inside(x - dx, y - dy) { + continue; + } + let mut n = 1; + while inside(x + n * dx, y + n * dy) { + n += 1; + } + let thickness = n as f32 * step; + for t in 0..n { + let slot = &mut sections[(y + t * dy) as usize * width + (x + t * dx) as usize]; + *slot = slot.min(thickness); + } + } + } + sections.retain(|v| v.is_finite()); + if sections.is_empty() { + return None; + } + let middle = sections.len() / 2; + let (_, value, _) = sections.select_nth_unstable_by(middle, f32::total_cmp); + Some(*value) +} + +enum Shape { + Circle, + Rectangle, + Diamond, +} + +pub(super) struct Frame { + shape: Shape, + center: Point, + half_width: f32, + half_height: f32, +} + +pub(super) fn nodes( + glyphs: &mut Glyphs<'_>, + circuit: &Circuit, + draw: &Drawing, + size: f32, + depth: usize, + children: &mut Vec, +) -> Result> { + let mut result = Vec::new(); + let mut label_pixels = 0; + for node in &circuit.decorations { + let shape = match node.kind.as_str() { + "circle" => Shape::Circle, + "rectangle" => Shape::Rectangle, + "diamond" => Shape::Diamond, + _ => continue, + }; + if result.iter().any(|f: &Frame| f.center == node.point) { + return Err(Error::new("invalid_layout", "流程图的节点中心不能重合")); + } + let label = glyphs.sequence_at(&crate::text::parse(&node.text), size, depth + 1)?; + label_pixels += label.mask.len(); + if label_pixels > 16_000_000 { + return Err(Error::new("invalid_layout", "流程图节点文字超过内存预算")); + } + let unit = |pixels: u32| (pixels as f32 / 2. + 0.18 * size) / draw.scale; + let (w, h) = (unit(label.mask.width()), unit(label.mask.height())); + let (half_width, half_height) = match shape { + Shape::Circle => { + let r = w.hypot(h); + (r, r) + } + Shape::Rectangle => (w, h), + Shape::Diamond => (2. * w, 2. * h), + }; + let (x, y) = draw.point(node.point); + let xy = ( + x - (label.left + label.right()) / 2, + y - (label.top + label.bottom()) / 2, + ); + children.push((label, xy.0, xy.1)); + result.push(Frame { + shape, + center: node.point, + half_width, + half_height, + }); + } + Ok(result) +} + +impl Frame { + fn boundary(&self, towards: Point) -> Point { + let (dx, dy) = (towards.0 - self.center.0, towards.1 - self.center.1); + let (x, y) = (dx.abs() / self.half_width, dy.abs() / self.half_height); + let divisor = match self.shape { + Shape::Circle => x.hypot(y), + Shape::Rectangle => x.max(y), + Shape::Diamond => x + y, + }; + Point(self.center.0 + dx / divisor, self.center.1 + dy / divisor) + } + + pub(super) fn outline(&self, draw: &mut Drawing) { + let Point(x, y) = self.center; + let (w, h) = (self.half_width, self.half_height); + if let Shape::Circle = self.shape { + // 在斜向箭头与圆的交点也采样,确保圆弧和箭尖共享同一像素。 + let mut angles: Vec<_> = (0..48).map(|i| TAU * i as f32 / 48.).collect(); + for p in &draw.contacts { + let (dx, dy) = (p.0 - x, p.1 - y); + if (dx.hypot(dy) - w).abs() < 0.0001 { + angles.push(dy.atan2(dx).rem_euclid(TAU)); + } + } + angles.sort_by(f32::total_cmp); + angles.push(TAU); + draw.path( + angles + .into_iter() + .map(|a| Point(x + w * a.cos(), y + h * a.sin())) + .collect(), + ); + return; + } + let corners = match self.shape { + Shape::Rectangle => [ + Point(x - w, y - h), + Point(x + w, y - h), + Point(x + w, y + h), + Point(x - w, y + h), + ], + _ => [ + Point(x - w, y), + Point(x, y - h), + Point(x + w, y), + Point(x, y + h), + ], + }; + for i in 0..4 { + draw.line(corners[i], corners[(i + 1) % 4]); + } + } +} + +pub(super) fn clip(segment: &Segment, nodes: &[Frame]) -> Result { + let endpoint = |start: Point, end: Point| { + nodes + .iter() + .find(|f| f.center == start) + .map_or(start, |f| f.boundary(end)) + }; + let mut clipped = segment.clone(); + clipped.start = endpoint(segment.start, segment.end); + clipped.end = endpoint(segment.end, segment.start); + let (dx, dy) = ( + segment.end.0 - segment.start.0, + segment.end.1 - segment.start.1, + ); + if (clipped.end.0 - clipped.start.0) * dx + (clipped.end.1 - clipped.start.1) * dy <= 0. { + return Err(Error::new( + "invalid_layout", + "流程图连线太短,请增大相邻节点或折点的间距", + )); + } + Ok(clipped) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{FontBook, text}; + + #[test] + fn flowchart_labels_and_outlines_follow_the_selected_body_font_and_size() { + let folder = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/font_assets"); + let chart = |s: &str| { + text::circuit::parse(&format!( + r"\begin{{circuitikz}}[flowchart]{s}\end{{circuitikz}}" + )) + .unwrap() + }; + for font in ["华阳手写体.ttf", "李国夫手写体.ttf"] { + let book = FontBook::new(&std::fs::read(folder.join(font)).unwrap(), &[]).unwrap(); + let mut glyphs = Glyphs::new(&book); + for size in [24., 34., 48.] { + let condition = "i ≤ 10"; + let label = glyphs + .circuit( + &chart(&format!(r"\draw (0,0) node[right]{{{condition}}};")), + size, + 0, + ) + .unwrap(); + let body = glyphs.sequence(&text::parse(condition), size).unwrap(); + assert_eq!(label.mask, body.mask, "{font} {size} condition"); + let body = glyphs.sequence(&text::parse("B6"), size).unwrap(); + let node = glyphs + .circuit(&chart(r"\draw (0,0) node[rectangle]{B6};"), size, 0) + .unwrap(); + let (w, h) = node.mask.dimensions(); + let (bw, bh) = body.mask.dimensions(); + assert!( + (0..=w - bw).any(|x| (0..=h - bh).any(|y| image::imageops::crop_imm( + &node.mask, x, y, bw, bh + ) + .to_image() + == body.mask)), + "{font} {size} node label" + ); + let border: f32 = (0..h) + .map(|y| f32::from(node.mask[(w / 2, y)][0]) / 255.) + .take_while(|v| *v > 0.) + .sum(); + let measured = pen_width(book.primary(), size, glyphs.pen.thickness(size)); + assert!( + (border - measured).abs() < 0.01, + "{font} {size} border: {border}" + ); + let solid_width = (0..h) + .map(|y| node.mask[(w / 2, y)][0]) + .take_while(|v| *v > 0) + .filter(|v| *v >= 128) + .count(); + assert_eq!(solid_width, measured.round() as usize, "{font} {size}"); + } + } + } + + #[test] + fn edges_stop_at_shaped_boundaries_in_writing_direction() { + let source = r"\begin{circuitikz}[flowchart]\draw[->] (0,0) -- (4,4);\end{circuitikz}"; + let segment = &text::circuit::parse(source).unwrap().segments[0]; + for (shape, first) in [ + (Shape::Circle, 2_f32.sqrt()), + (Shape::Rectangle, 2.), + (Shape::Diamond, 1.), + ] { + let nodes = [ + Frame { + shape, + center: Point(0., 0.), + half_width: 2., + half_height: 2., + }, + Frame { + shape: Shape::Rectangle, + center: Point(4., 4.), + half_width: 0.5, + half_height: 0.75, + }, + ]; + let clipped = clip(segment, &nodes).unwrap(); + assert!( + (clipped.start.0 - first).abs() < 0.0001 + && (clipped.start.1 - first).abs() < 0.0001 + ); + assert_eq!(clipped.end, Point(3.5, 3.5)); + assert!(clipped.end_arrow); + } + } +} diff --git a/crates/handwriting-core/src/render/illustration.rs b/crates/handwriting-core/src/render/illustration.rs index 435c655b..2433dd24 100644 --- a/crates/handwriting-core/src/render/illustration.rs +++ b/crates/handwriting-core/src/render/illustration.rs @@ -150,6 +150,7 @@ pub(super) fn tiles( imageops::replace(&mut padded, &mask, PAD.into(), PAD.into()); Tile { is_text: false, + is_native_diagram: false, id: part, illustration: Some(id), x: x + dx as i32 - PAD as i32, diff --git a/crates/handwriting-core/src/text/circuit.rs b/crates/handwriting-core/src/text/circuit.rs index 8fe990d3..62cbac45 100644 --- a/crates/handwriting-core/src/text/circuit.rs +++ b/crates/handwriting-core/src/text/circuit.rs @@ -28,6 +28,7 @@ pub struct Decoration { #[derive(Debug, Clone, PartialEq)] pub struct Circuit { pub american: bool, + pub flowchart: bool, pub segments: Vec, pub decorations: Vec, } @@ -173,6 +174,8 @@ impl<'a> Parser<'a> { } [kind] if ANCHORS.contains(kind) + || (self.circuit.flowchart + && matches!(*kind, "circle" | "rectangle" | "diamond")) || matches!(*kind, "" | "ground" | "rground" | "circ" | "ocirc") => { (self.current, *kind) @@ -297,6 +300,7 @@ pub fn parse(source: &str) -> Option { names: HashMap::new(), circuit: Circuit { american: false, + flowchart: false, segments: Vec::new(), decorations: Vec::new(), }, @@ -309,6 +313,7 @@ pub fn parse(source: &str) -> Option { let options = p.group('[', ']')?; for option in split_options(&options)? { match option { + "flowchart" => p.circuit.flowchart = true, "american" | "american resistors" => p.circuit.american = true, "RPvoltages" | "voltage dir=RP" => p.rp = true, "thin" | "semithick" | "thick" => (), @@ -337,7 +342,7 @@ pub fn parse(source: &str) -> Option { return None; } } - if p.circuit.segments.is_empty() { + if p.circuit.segments.is_empty() && (!p.circuit.flowchart || p.circuit.decorations.is_empty()) { None } else { Some(p.circuit) diff --git a/crates/handwriting-core/src/text/circuit/labels.rs b/crates/handwriting-core/src/text/circuit/labels.rs index a6495024..20942183 100644 --- a/crates/handwriting-core/src/text/circuit/labels.rs +++ b/crates/handwriting-core/src/text/circuit/labels.rs @@ -82,6 +82,7 @@ impl Parser { "pm" => "±", "le" | "leq" => "≤", "ge" | "geq" => "≥", + "ne" | "neq" => "≠", "infty" => "∞", "angle" => "∠", "circ" => "°", diff --git a/crates/handwriting-core/tests/behavior.rs b/crates/handwriting-core/tests/behavior.rs index 31d63cf7..7d443497 100644 --- a/crates/handwriting-core/tests/behavior.rs +++ b/crates/handwriting-core/tests/behavior.rs @@ -245,6 +245,32 @@ fn full_page_illustration_paginates_and_half_scale_leaves_room_for_text() { assert_eq!(pages(&full).len(), 2); assert_eq!(pages(&half).len(), 1); } +#[test] +fn illustration_keeps_selected_pen_when_text_is_rendered_as_an_ink_layer() { + use base64::{Engine, engine::general_purpose::STANDARD}; + let image = RgbaImage::from_fn(80, 40, |x, y| { + if (10..65).contains(&x) && (15..20).contains(&y) { + Rgba([0, 0, 0, 255]) + } else { + Rgba([255; 4]) + } + }); + let data = STANDARD.encode(export::png(&image).unwrap()); + let mut r = request(&format!("![diagram](data:image/png;base64,{data})")); + r.params.ink_layers = true; + r.params.fill = [150, 20, 40, 255]; + r.params.ink_opacity = 75; + r.params.illustration_uses_pen = true; + for fine in [false, true] { + r.params.fine_edit = fine; + assert!( + pages(&r)[0] + .pixels() + .any(|p| p[0].saturating_sub(p[1]) > 40) + ); + } +} + fn docx_bytes(xml: &str) -> Vec { let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new())); zip.start_file( diff --git a/crates/handwriting-core/tests/circuitikz.rs b/crates/handwriting-core/tests/circuitikz.rs index 3d498026..eb092dcb 100644 --- a/crates/handwriting-core/tests/circuitikz.rs +++ b/crates/handwriting-core/tests/circuitikz.rs @@ -69,6 +69,19 @@ fn relative_coordinates_reference_and_named_coordinates_remain_exact() { ] ); } + +#[test] +fn framed_nodes_are_opt_in_and_keep_named_edges_and_conditions() { + let body = r"\coordinate (rhs) at (4,1); + \draw (0,0) node[rectangle]{B3}; \draw (rhs) node[diamond]{B5}; + \draw[->] (0,0) -| (rhs) node[midway,left]{$t\neq 0$};"; + assert!(circuit::parse(&env(body)).is_none()); + let graph = circuit::parse(&env(&format!("[flowchart]{body}"))).unwrap(); + assert!(graph.flowchart); + assert_eq!(graph.decorations[2].text, "t≠ 0"); + assert_eq!(graph.segments[1].end, circuit::Point(4., 1.)); + assert!(graph.segments[1].end_arrow); +} #[test] fn flowchart_conditions_follow_their_wire_without_moving_its_endpoint() { let source = env(r"\draw[->] (0,0) -- (4,2) node[midway,above] {$i\le10$} diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index 0521dd08..2dbebd45 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -443,6 +443,7 @@ fn fine_edit_moves_one_homework_character_and_exports_the_same_pages() { scale: 115, angle: 12, opacity: 83, + opacity_ramp: None, color: Some([167, 12, 36]), thickness: 7, warp: Some([1., 0., 0., 0., 1., 0., 0.004, 0.]), diff --git a/crates/handwriting-server/src/lib.rs b/crates/handwriting-server/src/lib.rs index 0a4ffa2d..8a537a59 100644 --- a/crates/handwriting-server/src/lib.rs +++ b/crates/handwriting-server/src/lib.rs @@ -273,7 +273,7 @@ async fn read_local_font( } async fn version(State(s): State) -> Json { Json( - 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}}), + serde_json::json!({"version":s.0.config.version,"capabilities":{"local_fonts":s.0.local_fonts.is_some(),"task_cancellation":true,"task_submission_id":true,"export_blur":true,"fine_edit":true}}), ) } struct Upload { diff --git a/crates/handwriting-server/src/render_job.rs b/crates/handwriting-server/src/render_job.rs index 985cf158..4ce06058 100644 --- a/crates/handwriting-server/src/render_job.rs +++ b/crates/handwriting-server/src/render_job.rs @@ -157,7 +157,7 @@ impl ResultFormat { Self::Pdf } else if !params.preview { Self::Zip - } else if params.ink_layers { + } else if params.preview_ink_layers() { Self::InkLayers } else if params.full_preview { Self::Images diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 9c91becf..b33317f4 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -70,7 +70,7 @@ cargo build --locked --release -p panache-mcp | 工具 | 用法 | | --- | --- | -| `list_fonts` | 按名称、文件名或来源(`bundled`、`user`、`system`)检索字体。默认 20 项,使用 `next_offset` 翻页。为作业、实验报告选笔迹时,指导模型展示中英数混排小样,按用户偏好定稿。 | +| `list_fonts` | 按名称、文件名或来源(`bundled`、`user`、`system`)检索字体。默认 20 项,使用 `next_offset` 翻页。传入 `sample` 可在稿件的纸张上比较当前字体和一至两个候选字体。 | | `save_section` | 用 `markdown` 新建稿件。首次可传标题、字体、字号、纸样、墨色、种子和作业排版模式。返回 `draft_id`、版本号和节号。 | | `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 | | `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 | @@ -88,6 +88,14 @@ cargo build --locked --release -p panache-mcp 例如用 `list_fonts(query="楷", source="system", limit=8)` 检索系统字体。把 `entries[].id` 用于建稿的 `style.font` 或调稿的 `changes.font`。随包字体继续接受原文件名。个人和系统字体会随稿保存,删除源文件后仍可预览历史版本。TTF、OTF 和 TTC/OTC 中带轮廓、单个字面大小不超过 32 MiB 的字体可供选择。 +给照片作业选字时,先用正文中的一行试排,例如“基本块 B1(1~2),if i > 10”。在精修位置前调用 `list_fonts`: + +```json +{"sample":{"draft_id":"稿件 ID","revision":1,"fonts":["华阳手写体.ttf","李国夫手写体.ttf"],"crop":[200,300,580,160]}} +``` + +`crop` 是原图的左、上、宽、高。请替换为稿件实际文字所在位置;省略时比较整页。客户端会收到标有字体的图片。选中候选后使用其 `tune_arguments`。图中标签若由外部程序绘制,应在绘制时采用选定字体。新作业的嵌入图沿用正文笔色、透明度、粗细和柔化;已有稿件可用 `tune_handwriting(changes={"illustration_uses_pen":true}, preserve_local_adjustments=true)` 启用。 + 桌面与 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)。 @@ -134,18 +142,61 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ ## 照片排版与成品复盘 +一道模拟理工科作业,分别用 MCP 排在两张无横线的纸张照片上。点击成稿可查看原尺寸 PNG。 + +| 斜拍的无横线白纸 | 花影下的白纸 | +| --- | --- | +| [![木桌上的斜拍白纸,手写代码、基本块与流程图沿纸边排列](../../assets/examples/angled-sheet-5ad065421e7c.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/922b6c7303c6a1d86271e42929bb316eb9c953bb/screenshots/worksheet-lettering/round-7/worksheet.png) | [![花头遮住部分右侧纸边,手写作业与流程图避开花头](../../assets/examples/flower-shadow-a07835481c3a.webp)](https://raw.githubusercontent.com/SXP-Simon/Panache/1aea40070e551868368842392ca349a823d95de0/screenshots/worksheet-lettering/round-8/worksheet.png) | + +底图摄影 · [Kaboompics](https://www.pexels.com/photo/empty-paper-sheet-on-wooden-table-4207708/) · [Andrzej Gdula](https://www.pexels.com/photo/white-printer-paper-on-brown-wooden-table-11485123/) + 1. 表格、无横线纸和画作均可排字。用户已指定位置或委托选位时,直接按意图排版。落字区有歧义时,简短问“要写在哪个栏,哪些地方留白?”若必填区域在画外,或失焦、遮挡、透视已使它无法定位,建稿前指出具体缺哪一块,请用户补拍该区域或确认只填可见部分。已明确要求只写正文时,直接填写可定位的正文区。 2. 用 `save_section` 导入照片并保留版本号。用 `preview_handwriting(view="review")` 取得同一页的底纸、成品和叠图。整页复查图长边最多 900 像素,像素坐标以返回的 `photo_size` 为准。检查有字区域的横线、页眉、页边和需要保留的图案。 3. 调用 `tune_handwriting(draft_id, expected_revision, paper_guides, note)` 在原照片上重排全文。至少给两条参考线,每条提供行号与左右端点。无横线纸也可以指定想写入的区域。传空数组恢复建稿时的校准。旧版本仍可回看;改写书写区域会重置冲突的边距覆盖,重新排版后需重新选字。 -4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和这次布局返回的版本交给 `adjust_glyphs`。用户点名要改哪几个字时,按 `ids` 的顺序传 `expected_texts`,例如 `ids=[4,6], expected_texts=["春","雨"]`。任一编号对应的文字不符,整批都不保存;版本冲突时重新查布局并定位。相同的字出现多次时,用上下文或位置区分。纯位置选区和旧客户端可以省略文字核对。`place_center` 将一组字移到指定照片位置;`target_quad` 按左上、右上、右下、左下四角放置所选字块,替换该组已有几何调整。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 +4. 局部改动用 `preview_handwriting(view="layout", region=[[x,y],…])` 圈选字形中心,结果按页分批。把选中的 ID 和这次布局返回的版本交给 `adjust_glyphs`。用户点名要改哪几个字时,按 `ids` 的顺序传 `expected_texts`,例如 `ids=[4,6], expected_texts=["春","雨"]`。任一编号对应的文字不符,整批都不保存;版本冲突时重新查布局并定位。相同的字出现多次时,用上下文或位置区分。纯位置选区和旧客户端可以省略文字核对。同一原始行的文字用 `natural_line={"start":[x0,y0],"end":[x1,y1]}` 沿照片上的书写基线定位。默认保留原字号和字宽,短行留白;超长时可换行或扩大可用范围。多行需要统一缩放时使用相同的 `scale_percent`。`place_center` 平移字块;明确需要铺满四角时用 `target_quad`,回执给出纸面字形中心的最大主次轴伸缩比。局部字形还可分别调倾斜、浓度和笔画。调整后复查新版本。 5. 用 `read_section(view="trajectory")` 回看该稿的近期操作、简短调整理由和按页记录的复盘指标。有下一页时,把 `next_cursor` 作为下一次调用的 `cursor`。把需要人判断的歧义带回当前会话;确定符合用途后导出同一版本。 要核对局部改动,用 `preview_handwriting(view="review", region=…, revision=新版本, compare_revision=旧版本)` 查看同一区域的底纸、改前和改后图。移动字块时还可用 `previous_region` 圈出旧位置。需要保护的文字或页眉可单独圈选复查。区域使用原尺寸成品像素。[局部坐标与测量示例](tool-design.md#局部改动的复查) +在照片上画新的流程图时,把下例直接写入节的 Markdown。节点文字继承稿件的字体,图框和箭头按其笔画绘制。先给分支条件、箭头和节点留够空间,再移动整图。把图缩进小格会连同标签字号一起改变。已有位图的标签保存在像素中,需要改字形时可从已知题意重建节点和连线。 + +```tex +\begin{circuitikz}[flowchart] +\draw (0,0) node[rectangle]{B1}; +\draw (0,-2) node[diamond]{B2}; +\draw[->] (0,0) -- (0,-2) node[midway,right]{i≤10}; +\end{circuitikz} +``` + +照片上的流程图、图标及插图应和正文落在同一纸面上。整页或局部 `view="review"` 的 `diagram_perspective_check` 给出图框当前四角、同位置沿纸面两轴的参考四角、四边的方向差以及底边/顶边宽度比。用 `preview_arguments` 比较原纸与成稿,必要时用 `native_image_arguments` 放大看节点、箭头和标签。沿图上下边比对原纸横线,再沿左右侧比对页边、表格竖线或连续横线的端点。纸面模型可能只校准了旋转;没有足够参照时保留不确定性。根据模型得到的四角不构成四个独立实测点。 + +整体已协调时保留原图。图和字都偏时先核对纸张标定;仅图形偏斜、且原纸有清楚的四角参照时,用当前版 `layout_arguments` 找根 ID,调用 `adjust_glyphs(whole_drawing=true, ids=[根ID], target_quad=四角)`。四角按左上、右上、右下、左下填写。只移动整图用 `place_center`。独立位图标签随根图共同变换;原先手动挪过的标签可用 `separate_detail_alignment` 核对。四角操作从原始图块布局重建,单纯平移保留局部几何编辑。修后复看相同区域和附近正文。`view="layout", drawings_only=true` 列出整图;`illustrations_only=true` 仍可选取位图的独立细节。 + +照片建稿和预览返回的 `paper_focus_check` 可用于比较不同位置印刷边缘的过渡宽度。请在推荐的原尺寸局部内对照底纸和成品,看同一位置的印字、细横线、手写字和图线。清晰度渐变时连同中间过渡区一起看。确有不协调时只选受影响的字或图块轻调柔化,复查改动区和原先清晰的区域。空白或低反差区域可能缺少测量依据。 + +判断照片上的字是否过重时,在整页复核的 `local_paper_ink_check` 中先找第一行,再比较中、下部的样本。按 `preview_arguments` 打开原尺寸的底纸和成稿,留意相邻的印字和细线。纸面亮度、印字浓淡和笔画清晰度是三种不同的线索。若标题比同处印字明显更深,可用 `layout_arguments` 定位字形,逐行调整 `adjust_glyphs.opacity`,以 `compare_revision` 查看交界与原先合适的区域。单个图块跨过深浅边界时,`opacity_ramp=[[0,65],[60,100]]` 会从图块顶部的 65% 逐渐过渡到高度 60% 处的 100%,下段维持原浓度。这些百分比乘在该字形原有的 opacity 上。 + +用户希望输出更接近轻微虚焦的照片时,先用 `preview_handwriting(view="image", export_blur_px=0.6, region=…)` 与同区域的 `0` 档比较。客户端可能缩放整页,局部裁图保留原始像素。选定后对同一稿件版本调用 `export_handwriting(format="zip", export_blur_px=0.6)`。数值为高斯模糊的标准差,范围 0–2 个输出像素。默认值为 0。纸与墨在合成后一起柔化,透明页保留透明度。PDF 和稿件自身的设置独立于这项 PNG 交付选项。 + +普通导出省略柔化参数。仅要求「稍微柔一点」时,可从均匀的 `export_blur_px=0.6` 试起。若指定上软下清、右上角偏软等方向,改用 `export_blur_gradient`,在同一版的预览和 ZIP 导出中传相同的对象。例如: + +```json +{ + "from": { "x": 0.5, "y": 0.12, "sigma_px": 0.8 }, + "to": { "x": 0.5, "y": 0.60, "sigma_px": 0.0 } +} +``` + +两个点的 `x/y` 以最终整张图片为参照,左上角为 (0,0),右下角为 (1,1)。`sigma_px` 的单位是原图像素。强度按沿两点连线的像素距离比例平滑改变,两端以外维持端点值。上例在纸面上部使用 0.8 px,自高度 12% 起逐渐变清晰,60% 以下保留原像素。把两点放在一条斜线上即可指定斜向渐变。更换或旋转底图时,按新整页重新选点。两种柔化参数只能选一种。用 `view="image"` 和 `region` 分别查看两个端点及中间区域;局部复用整页的坐标和效果。 + +照片 PNG 的整页或局部复查可能返回 `png_finish_comparison`。在同版的两个参考区分别用 `clear` 和 `gradient` 原样调用 `preview_handwriting`,核对偏软一侧的纸与笔迹是否更协调,以及清晰一侧的小字是否完整。两端取自同方向可比的纸面印迹;较宽的印刷边缘也可能来自纸张或印刷。需要时可把两档裁区同步移到附近字迹。两档差别很小或细字变淡时,可直接交付清晰版。 + 作业表可用正文横线设置参考线,将同一页的课程、姓名等字块分别定位。若侧栏印字自下往上读,将原字块的左上、右上、右下、左下四角依次投到侧栏的左下、左上、右上、右下。复查时按栏核对读向、印字和留给老师的评分区。`changed_pixels_outside_reference` 也会计入正文参考区外有意填写的表头和侧栏,应结合这些栏位解读。 客户端已知目标值时,可在 `tune_handwriting` 中同时传 `changes={"perturb_theta_sigma":0.07}` 和 `readback_variation=["perturb_theta_sigma"]`。成功回执的 `effective_changes` 给出写入前后的有效值,用于直接核对本次写入,省去事后再读一次。最多点名本次提交的两个 `variation` 控件。提交 `null` 时读回继承值,有效值相同的键会省略。若要根据旧值决定改多少,仍应先用 `describe_controls` 读取该稿当前版本的值。 +同页复盘在有可比样本时给出 `adjacent_row_check` 和 `illustration_ink_check`。复用其 `preview_arguments`,或逐项调用 `separate_preview_arguments`,在原图尺度看邻行字宽和图线附近的正文。`evidence.adjacent_rows` 分别记录两行的横纵伸缩比和照片投影前的垂直缩放,能区分字被拉宽和整行等比放大,`evidence.illustration_contrast` 记录采样区相对底纸的亮度下降及像素数。同一回执的 `ink_footprint_width_px` 用新增墨迹的面积与周长估算有效宽度,单位为原图像素。标签结构和节点交点都会影响数值,仍需看同倍率裁图中的具体字干、框线和箭杆。 + 如果字像贴在照片上,先分清是墨迹边缘过锐,还是纸面光照、阴影或墨色对比造成的观感。例如,纸面右侧有阴影,但用户认为笔画已经合适,就保留原样。如果用户明确指出笔画边缘过锐,或原尺寸成品裁图中的笔画边缘确实比附近可比的实拍印字或横线更锐,可以小幅柔化试一版。比如用户说“只改第一行,第二行保留”,用 `preview_handwriting(view=layout)` 找到第一行对应的字,再用 `adjust_glyphs` 的 `softness` 只调这些字。只有用户要调整整份稿子时,才用 `tune_handwriting` 的 `ink_softness`。用户要求保留墨迹时,直接沿用原版。 需要核对时,照片整页复盘的 `photo_appearance.preview_arguments` 可直接交给 `preview_handwriting`。有页内文字基线样本时,会返回字迹附近的原尺寸底纸和成品裁图,也可以自己圈选。试调后在新版本沿用原选区,用 `compare_revision` 指向旧版本,对照底纸、改前和改后三张实际裁图:底纸用来看原有阴影和印记,两张成品用来看细笔是否糊掉、对比度是否下降。如果用户点名第二行要保留,也对照第二行的改前和改后。效果变差或拿不准就保留原版。只有文字回执时,把用户观察到的情况说清楚,例如“你觉得边缘已经合适”;还需要目视判断时,请用户看裁图。字号与可写空间是否相称可另查 `layout` 或 `typography` 组。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比;只改墨迹组参数会保留已有的单字移位和透视调整。更换字体、字号或参考线后,应在新版本重新检查选区。 diff --git a/crates/panache-mcp/src/controls.json b/crates/panache-mcp/src/controls.json index 7ff757f5..7eed2221 100644 --- a/crates/panache-mcp/src/controls.json +++ b/crates/panache-mcp/src/controls.json @@ -29,6 +29,7 @@ "latin_digits": {"type":"boolean","default":false,"description":"Leave unset on new drafts. False keeps 0–9 at the main font and size. True applies the Latin size and any selected Latin font to digits."} }, "ink": { + "illustration_uses_pen": {"type":"boolean","description":"Render embedded diagram strokes and labels using the manuscript ink color, opacity, thickness and softness. The shapes and lettering in the source image stay as drawn."}, "transparent_background": {"type":"boolean","description":"Ink-only PNG preview and ZIP. PDF retains the paper."}, "ink": {"type":"color"}, "ink_alpha": {"type":"integer","min":0,"max":255,"description":"Alpha channel of the selected RGBA pen color, before ink opacity."}, diff --git a/crates/panache-mcp/src/controls.rs b/crates/panache-mcp/src/controls.rs index 52b3c07b..78a156b3 100644 --- a/crates/panache-mcp/src/controls.rs +++ b/crates/panache-mcp/src/controls.rs @@ -97,6 +97,7 @@ pub fn parameters(draft: &Snapshot<'_>, section: u32, changes: &Changes) -> Resu top_margin: 62., bottom_margin: 55., fill: style.ink_rgba()?, + illustration_uses_pen: style.illustration_uses_pen.unwrap_or(false), strikethrough_probability: 0., perturb_x_sigma: 1., perturb_y_sigma: 1., diff --git a/crates/panache-mcp/src/drafts.rs b/crates/panache-mcp/src/drafts.rs index 9ffa06a9..8a80527f 100644 --- a/crates/panache-mcp/src/drafts.rs +++ b/crates/panache-mcp/src/drafts.rs @@ -84,6 +84,13 @@ pub struct Snapshot<'a> { } impl Snapshot<'_> { + pub fn font_name(&self) -> &str { + self.controls + .get("font") + .and_then(Value::as_str) + .unwrap_or(&self.style.font) + } + pub fn review_section(&self, requested: Option) -> Result { if let Some(section) = requested { ensure!(section > 0, "section starts at 1"); diff --git a/crates/panache-mcp/src/engine.rs b/crates/panache-mcp/src/engine.rs index 796614c3..7a18307c 100644 --- a/crates/panache-mcp/src/engine.rs +++ b/crates/panache-mcp/src/engine.rs @@ -1,4 +1,6 @@ mod adjustments; +pub(crate) use handwriting_core::export_blur; +pub(crate) mod font_samples; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use handwriting_core::{Cancellation, FontBook, Limits, RenderRequest, export}; @@ -12,6 +14,16 @@ use crate::{ use handwriting_core::fine_edit::{self, Adjustment, Adjustments}; use serde_json::{Value, json}; +fn drawing_kind(g: &fine_edit::GlyphBounds) -> Option<&'static str> { + if g.is_native_diagram { + Some("native_diagram") + } else if g.illustration == Some(g.id) { + Some("illustration") + } else { + None + } +} + fn glyph_source<'a>(text: &'a [u16], glyph: &fine_edit::GlyphBounds) -> Option<&'a [u16]> { let [start, end] = glyph.source_utf16?; text.get(start as usize..end as usize) @@ -44,6 +56,33 @@ fn glyph_point( ] } +// 2026-11-27:以同一外框变换预测拆分标签的位置,与各标签实际几何在照片像素中对照。 +fn detail_corner_gap( + draft: &Snapshot<'_>, + parent: &fine_edit::GlyphBounds, + edit: Option<&Adjustment>, + parts: &[&fine_edit::GlyphBounds], + edits: &HashMap, +) -> f32 { + let mut max_gap = 0.0f32; + let center = glyph_point(parent, None, [0., 0.]); + let project = |g, e, uv| crate::review::photo_point(draft, glyph_point(g, e, uv)); + for part in parts { + let (w, h) = ( + f64::from(part.bounds[2]) / 2., + f64::from(part.bounds[3]) / 2., + ); + for uv in [[-w, -h], [w, -h], [w, h], [-w, h]] { + let point = glyph_point(part, None, uv); + let relative = std::array::from_fn(|i| f64::from(point[i] - center[i])); + let expected = project(parent, edit, relative); + let actual = project(part, edits.get(&part.id).copied(), uv); + max_gap = max_gap.max((actual[0] - expected[0]).hypot(actual[1] - expected[1])); + } + } + max_gap +} + #[derive(Clone)] pub struct RenderedPreview { pub png: String, @@ -119,17 +158,16 @@ impl Engine { background: Option>, edits: Option, ) -> Result { - let font_name = draft - .controls - .get("font") - .and_then(serde_json::Value::as_str) - .unwrap_or(&draft.style.font); + let primary = self.draft_font(draft, draft.font_name())?; + self.request_with_font(draft, section, background, edits, primary) + } + fn draft_font(&mut self, draft: &Snapshot<'_>, font_name: &str) -> Result> { ensure!( font_name.starts_with("upload:") || self.names.iter().any(|f| f == font_name), "Font no longer available: {}", font_name ); - let primary = if font_name.starts_with("upload:") { + Ok(if font_name.starts_with("upload:") { let key = format!("{}:{}", draft.id, font_name); if let Some(font) = self.fonts.get(&key) { font.clone() @@ -140,7 +178,16 @@ impl Engine { } } else { self.font(font_name)? - }; + }) + } + fn request_with_font( + &mut self, + draft: &Snapshot<'_>, + section: Section, + background: Option>, + edits: Option, + primary: Arc, + ) -> Result { let fonts = FontBook::with_text_fallbacks(primary, §ion.text, |name| { if self.names.iter().any(|n| n == name) { self.font(name).map(Some) @@ -206,23 +253,8 @@ impl Engine { let camera = draft.camera(background.as_deref())?; let photo = Self::photo(draft, &mut background)?; let request = self.request(draft, section, background, edits)?; - let mut image = None; - let pages = - Self::render_pages(&request, photo.as_ref(), cancel, page_number, |i, page| { - if i + 1 == page_number { - image = Some(STANDARD.encode(camera.png(&page)?)); - } - Ok(()) - })?; - let png = image.ok_or_else(|| { - draft.page_error( - n, - handwriting_core::Error::new( - "invalid_page", - format!("Section has {pages} pages; requested {page_number}"), - ), - ) - })?; + let image = Self::render_page(draft, n, &request, photo.as_ref(), cancel, page_number)?; + let png = STANDARD.encode(camera.png(&image)?); let preview = RenderedPreview { png, fine_edit: request.params.fine_edit, @@ -276,6 +308,31 @@ impl Engine { None => handwriting_core::render::render_until_page(request, cancel, stop, emit), } } + fn render_page( + draft: &Snapshot<'_>, + section: u32, + request: &RenderRequest, + photo: Option<&(&handwriting_core::photo::PaperProjection, image::RgbaImage)>, + cancel: &Cancellation, + page_number: usize, + ) -> Result { + let mut image = None; + let pages = Self::render_pages(request, photo, cancel, page_number, |i, page| { + if i + 1 == page_number { + image = Some(page); + } + Ok(()) + })?; + image.ok_or_else(|| { + draft.page_error( + section, + handwriting_core::Error::new( + "invalid_page", + format!("Section has {pages} pages; requested {page_number}"), + ), + ) + }) + } pub fn page_count( &mut self, draft: &Snapshot<'_>, @@ -353,47 +410,65 @@ impl Engine { ) }) .collect(); - // Use edited geometry on this page. Raster details belong to the parent illustration. - let illustration_and_text = glyphs - .iter() - .find(|g| g.illustration == Some(g.id)) - .and_then(|g| { - let position = |g: &fine_edit::GlyphBounds, offset| { - crate::review::photo_point( - draft, - glyph_point(g, edits.get(&g.id).copied(), offset), - ) - }; - let hw = f64::from(g.bounds[2]) / 2.; - let hh = f64::from(g.bounds[3]) / 2.; - let corners = - [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]].map(|uv| position(g, uv)); - let bounds = |axis: usize| { - corners - .iter() - .map(|p| p[axis]) - .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), x| { - (lo.min(x), hi.max(x)) - }) - }; - let (left, right) = bounds(0); - let (top, bottom) = bounds(1); - let candidates = glyphs - .iter() - .filter(|v| v.is_text && edits.get(&v.id).is_none_or(|edit| edit.opacity > 0)); - let near = candidates.map(|v| position(v, [0., 0.])).min_by(|a, b| { - let distance = |p: &[f32; 2]| { - (p[0] - p[0].clamp(left, right)).hypot(p[1] - p[1].clamp(top, bottom)) - }; - distance(a).total_cmp(&distance(b)) - })?; - Some([ - [left.min(near[0]), top.min(near[1])], - [right.max(near[0]), bottom.max(near[1])], - ]) - }); + let mut text = Vec::new(); + let mut details = HashMap::>::new(); + for g in &glyphs { + if let Some(parent) = g.illustration + && parent != g.id + && !edits.get(&g.id).is_some_and(|e| e.hides_ink()) + { + details.entry(parent).or_default().push(g); + } + } + let mut drawings = Vec::new(); + let mut drawing_count = 0; + for g in &glyphs { + let edit = edits.get(&g.id).copied(); + let kind = drawing_kind(g); + let layout_offset = drawing_count; + drawing_count += usize::from(kind.is_some()); + if !(g.is_text || kind.is_some()) || edit.is_some_and(|v| v.hides_ink()) { + continue; + } + let hw = f64::from(g.bounds[2]) / 2.; + let hh = f64::from(g.bounds[3]) / 2.; + let paper_corners = + [[-hw, -hh], [hw, -hh], [hw, hh], [-hw, hh]].map(|uv| glyph_point(g, edit, uv)); + let corners = paper_corners.map(|p| crate::review::photo_point(draft, p)); + let bounds = crate::review::Bounds::from_corners(corners); + if let Some(kind) = kind { + drawings.push(crate::review::Drawing { + id: g.id, + kind, + layout_offset, + details: details.get(&g.id).map(|parts| { + ( + parts.len(), + detail_corner_gap(draft, g, edit, parts, &edits), + ) + }), + paper_corners, + photo_corners: corners, + }); + } else { + let edge = |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).hypot(a[1] - b[1]); + let width = edge(corners[0], corners[1]) + edge(corners[3], corners[2]); + let height = edge(corners[0], corners[3]) + edge(corners[1], corners[2]); + let dy = f64::from(g.baseline - g.bounds[1]) - hh; + let baseline = glyph_point(g, edit, [0., dy])[1]; + let top = glyph_point(g, edit, [0., -hh]); + let bottom = glyph_point(g, edit, [0., hh]); + text.push(crate::review::TextSample { + bounds, + baseline, + paper_vertical_scale: edge(top, bottom) / g.bounds[3] as f32, + stretch: (width / height) / (hw / hh) as f32, + }); + } + } Ok(crate::review::PageSample { - illustration_and_text, + text, + drawings, baselines, content_sha256: format!("{:x}", membership.finalize()), }) @@ -414,6 +489,9 @@ impl Engine { let req = self.fine_request(draft, section)?; let (_, mut bounds) = fine_edit::inspect_page(&req, page, cancel) .map_err(|error| draft.page_error(number, error))?; + if input.drawings_only == Some(true) { + bounds.retain(|g| drawing_kind(g).is_some()); + } if input.illustrations_only == Some(true) { bounds.retain(|g| g.illustration.is_some()); } @@ -448,6 +526,9 @@ impl Engine { if input.region.is_some() { row["selected_center"] = json!(center(g)); } + if let Some(kind) = drawing_kind(g) { + row["kind"] = json!(kind); + } if let Some(parent) = g.illustration { row["kind"] = json!(if parent == g.id { "illustration" @@ -508,7 +589,7 @@ impl Engine { writer: &mut crate::storage::BudgetWriter<'_>, draft: &Snapshot<'_>, sections: Vec
, - format: Format, + (format, finish): (Format, Option), cancel: &Cancellation, mut on_page: impl FnMut(usize, u32, usize, &image::RgbaImage), ) -> Result { @@ -549,7 +630,14 @@ impl Engine { } Format::Zip => { let mut zip = export::ZipExport::new(writer); - render_sections(&mut |i, page| zip.add_with_camera(i, page, &camera))?; + render_sections(&mut |i, page| { + if let Some(finish) = finish { + let finished = finish.apply(page, cancel)?; + zip.add_with_camera(i, &finished, &camera) + } else { + zip.add_with_camera(i, page, &camera) + } + })?; zip.finish()?; } }; diff --git a/crates/panache-mcp/src/engine/adjustments.rs b/crates/panache-mcp/src/engine/adjustments.rs index b224adab..2fb3df10 100644 --- a/crates/panache-mcp/src/engine/adjustments.rs +++ b/crates/panache-mcp/src/engine/adjustments.rs @@ -2,12 +2,12 @@ use super::{Engine, glyph_point, glyph_source}; use crate::{ Nudge, Shape, Style, drafts::{Section, Snapshot}, - placement::Placement, + placement::{Placement, PlacementReport}, }; use anyhow::{Context, Result, ensure}; use handwriting_core::{ Cancellation, Parameters, - fine_edit::{self, Adjustment, Adjustments, GlyphBounds}, + fine_edit::{self, Adjustment, Adjustments, GlyphBounds, OpacityRamp}, }; use serde_json::json; use std::collections::{BTreeMap, BTreeSet}; @@ -19,19 +19,31 @@ impl Engine { section: Section, input: &crate::Nudge, cancel: &Cancellation, - ) -> Result { + ) -> Result<(u32, Option, usize)> { let changes = GlyphChanges::parse(input, &draft.style)?; let version = section.version; let mut req = self.fine_request(draft, section)?; let (key, mut bounds) = fine_edit::inspect_page(&req, input.page, cancel) .map_err(|error| draft.page_error(input.section, error))?; - bounds.retain(|g| changes.ids.contains(&g.id)); + if input.whole_drawing { + let parent = input.ids[0]; + ensure!( + bounds + .iter() + .any(|g| g.id == parent + && (g.is_native_diagram || g.illustration == Some(parent))), + "Select one native diagram ID or raster illustration parent ID on this page" + ); + bounds.retain(|g| g.id == parent || g.illustration == Some(parent)); + } else { + bounds.retain(|g| changes.ids.contains(&g.id)); + } let mut selected = BTreeMap::new(); for glyph in &bounds { selected.entry(glyph.id).or_insert(glyph); } ensure!( - selected.len() == changes.ids.len(), + changes.ids.iter().all(|id| selected.contains_key(id)), "Glyph not on this page; inspect its layout first" ); if let Some(texts) = &input.expected_texts { @@ -55,6 +67,7 @@ impl Engine { .map(|e| (e.id, e)) .collect(); let geometry = Geometry::resolve(input, draft, &req.params, &bounds, &edits)?; + let affected: Vec<_> = selected.keys().copied().collect(); for (id, glyph) in selected { let edit = edits.entry(id).or_insert(Adjustment { id, @@ -63,6 +76,7 @@ impl Engine { scale: 100, angle: 0, opacity: 100, + opacity_ramp: None, color: None, thickness: 0, softness: 0, @@ -72,15 +86,26 @@ impl Engine { } ensure!(edits.len() <= 10000, "Section glyph edit limit reached"); cancel.check()?; - draft.store_edits( + let placement = match geometry { + Geometry::Placement(_, report) => Some(report), + _ => None, + }; + let mut history = json!({"page":input.page,"ids":input.ids,"place_center":input.place_center,"natural_line":input.natural_line,"target_quad":input.target_quad,"placement":placement,"dx":input.dx,"dy":input.dy,"scale":input.scale,"angle":input.angle,"shape":input.shape,"opacity":input.opacity,"opacity_ramp":input.opacity_ramp,"thickness":input.thickness,"softness":input.softness,"color":input.color,"note":input.note}); + if input.whole_drawing { + history["whole_drawing"] = json!(true); + history["drawing_id"] = json!(input.ids[0]); + history["ids"] = json!(affected); + } + let next = draft.store_edits( input.section, version, &Adjustments { key, glyphs: edits.into_values().collect(), }, - &json!({"page":input.page,"ids":input.ids,"place_center":input.place_center,"target_quad":input.target_quad,"dx":input.dx,"dy":input.dy,"scale":input.scale,"angle":input.angle,"shape":input.shape,"opacity":input.opacity,"thickness":input.thickness,"softness":input.softness,"color":input.color,"note":input.note}), - ) + &history, + )?; + Ok((next, placement, affected.len())) } } @@ -99,6 +124,25 @@ impl<'a> GlyphChanges<'a> { !ids.is_empty() && ids.len() == input.ids.len() && ids.len() <= 32, "Choose 1..32 distinct glyph IDs" ); + if input.whole_drawing { + ensure!( + ids.len() == 1 + && (input.target_quad.is_some() ^ input.place_center.is_some()) + && input.expected_texts.is_none() + && input.natural_line.is_none() + && input.dx.is_none() + && input.dy.is_none() + && input.scale.is_none() + && input.angle.is_none() + && input.shape.is_none() + && input.opacity.is_none() + && input.opacity_ramp.is_none() + && input.thickness.is_none() + && input.softness.is_none() + && input.color.is_none(), + "whole_drawing requires one drawing ID and only place_center or target_quad" + ); + } if let Some(texts) = &input.expected_texts { ensure!( texts.len() == input.ids.len() && texts.iter().all(|text| !text.is_empty()), @@ -107,12 +151,14 @@ impl<'a> GlyphChanges<'a> { } ensure!( input.target_quad.is_some() + || input.natural_line.is_some() || input.place_center.is_some() || input.dx.is_some() || input.dy.is_some() || input.scale.is_some() || input.angle.is_some() || input.opacity.is_some() + || input.opacity_ramp.is_some() || input.shape.is_some() || input.thickness.is_some() || input.softness.is_some() @@ -141,6 +187,12 @@ impl<'a> GlyphChanges<'a> { }; let thickness = input.thickness.map(delta).transpose()?; let softness = input.softness.map(delta).transpose()?; + ensure!( + input + .opacity_ramp + .is_none_or(|pair| OpacityRamp(pair).valid()), + "opacity_ramp requires two [height %, opacity %] anchors in 0..100 with increasing heights" + ); let color = input .color .as_ref() @@ -167,7 +219,7 @@ impl<'a> GlyphChanges<'a> { fn apply(&self, geometry: &Geometry, glyph: &GlyphBounds, e: &mut Adjustment) -> Result<()> { let input = self.input; - if let Geometry::Quadrilateral(map) = geometry { + if let Geometry::Placement(map, _) = geometry { map.apply(e, glyph.bounds)?; } if let Some(shape) = &input.shape { @@ -186,6 +238,9 @@ impl<'a> GlyphChanges<'a> { e.angle = input.angle.unwrap_or(e.angle); e.scale = input.scale.unwrap_or(e.scale); e.opacity = input.opacity.unwrap_or(e.opacity); + if let Some(pair) = input.opacity_ramp { + e.opacity_ramp = (pair[0][1] != 100 || pair[1][1] != 100).then_some(OpacityRamp(pair)); + } e.thickness = self.thickness.unwrap_or(e.thickness); e.softness = self.softness.unwrap_or(e.softness); if let Some(c) = self.color { @@ -223,7 +278,7 @@ fn shape_warp(shape: &Shape, height: i32) -> Option<[f64; 8]> { enum Geometry { Unchanged, - Quadrilateral(Placement), + Placement(Placement, PlacementReport), Translation([i32; 2]), } @@ -240,7 +295,14 @@ impl Geometry { .as_ref() .map(|p| p.photo_size.unwrap_or([p.width, p.height])) .unwrap_or([params.width.unwrap_or(0), params.height.unwrap_or(0)]); - if let Some(quad) = input.target_quad { + let projection = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); + let placement = match (&input.natural_line, input.target_quad) { + (Some(_), Some(_)) => anyhow::bail!("Use natural_line or target_quad separately"), + (Some(line), None) => Some(Placement::natural_line(projection, [w, h], bounds, line)?), + (None, Some(quad)) => Some(Placement::target_quad(projection, [w, h], bounds, quad)?), + (None, None) => None, + }; + if let Some((map, report)) = placement { ensure!( input.place_center.is_none() && input.dx.is_none() @@ -248,14 +310,9 @@ impl Geometry { && input.angle.is_none() && input.scale.is_none() && input.shape.is_none(), - "Use target_quad separately from other geometry fields" + "Use natural_line or target_quad separately from other geometry fields" ); - return Ok(Self::Quadrilateral(Placement::new( - draft, - [w, h], - bounds, - quad, - )?)); + return Ok(Self::Placement(map, report)); } if let Some(target) = input.place_center { ensure!( @@ -263,11 +320,13 @@ impl Geometry { "Use place_center separately from dx/dy/shape" ); ensure!(target[0] < w && target[1] < h, "Target outside the page"); - let projection = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); let dest = target.map(|v| v as f32); let dest = projection.map_or(dest, |p| p.paper_point(dest)); let mut mean = [0., 0.]; - for g in bounds { + for g in bounds + .iter() + .filter(|g| !input.whole_drawing || g.id == input.ids[0]) + { let pos = glyph_point(g, edits.get(&g.id), [0., 0.]); for axis in 0..2 { mean[axis] += pos[axis] / input.ids.len() as f32; diff --git a/crates/panache-mcp/src/engine/font_samples.rs b/crates/panache-mcp/src/engine/font_samples.rs new file mode 100644 index 00000000..f7524458 --- /dev/null +++ b/crates/panache-mcp/src/engine/font_samples.rs @@ -0,0 +1,169 @@ +use super::Engine; +use crate::{FontSample, State, reply}; +use anyhow::{Context, Result, ensure}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use handwriting_core::{Cancellation, FontBook, Limits, export}; +use image::{GenericImageView, RgbaImage, imageops}; +use rmcp::model::{CallToolResult, ContentBlock}; +use serde_json::json; + +const MAX_EDGE: u32 = 640; + +fn crop_image(image: &RgbaImage, crop: Option<[u32; 4]>) -> Result { + let [x, y, w, h] = crop.unwrap_or([0, 0, image.width(), image.height()]); + ensure!( + w > 0 + && h > 0 + && x.checked_add(w).is_some_and(|r| r <= image.width()) + && y.checked_add(h).is_some_and(|b| b <= image.height()), + "crop must be a nonempty rectangle within the {} × {} output", + image.width(), + image.height() + ); + let view = image.view(x, y, w, h); + let longest = w.max(h); + if longest <= MAX_EDGE { + return Ok(view.to_image()); + } + let size = |n| ((u64::from(n) * u64::from(MAX_EDGE)) / u64::from(longest)).max(1) as u32; + Ok(imageops::thumbnail(&*view, size(w), size(h))) +} + +pub(crate) fn compare( + state: &State, + engine: &mut Engine, + sample: FontSample, + cancel: &Cancellation, +) -> Result { + ensure!( + (1..=2).contains(&sample.fonts.len()), + "Supply one or two candidate font IDs" + ); + let draft = state.drafts.snapshot(&sample.draft_id, sample.revision)?; + let current = draft.font_name(); + let section_number = sample.section.unwrap_or(1); + let page = sample.page.unwrap_or(1); + ensure!( + (1..=Limits::default().max_pages).contains(&page), + "Invalid page number" + ); + let section = state + .drafts + .sections(draft.id, draft.revision, Some(section_number))? + .pop() + .context("Unknown section")?; + let (_, edits) = draft.edits(§ion)?; + let mut background = draft.background()?; + let photo = Engine::photo(&draft, &mut background)?; + let mut choices = vec![current]; + for id in &sample.fonts { + if !choices.contains(&id.as_str()) { + choices.push(id); + } + } + let mut data = json!({ + "draft_id":draft.id, "revision":draft.revision, "section":section_number, "page":page, + "crop":sample.crop, "current_font":current + }); + if choices.len() > 1 { + data["content_note"] = json!(if sample.crop.is_some() { + "各图取自同一页码和同一纸面位置。换字可能改变换行和分页,请核对裁区内的文字是否仍是同一句。" + } else { + "各图取相同页码。换字可能改变换行和分页,请按实际出现的文字比较。" + }); + if edits.is_some() { + data["placement_note"] = json!( + "当前样张保留本节手摆位置和其他局部调整。备选样张按新字体重新排版,采纳参数会保护已有调整。" + ); + } + } + let mut rows = Vec::new(); + let mut unavailable = Vec::new(); + let mut blocks = Vec::new(); + for id in choices { + cancel.check()?; + let (name, primary) = if id.starts_with("upload:") || engine.names.iter().any(|f| f == id) { + (id.to_owned(), engine.draft_font(&draft, id)?) + } else { + let (entry, bytes) = state.local_fonts.read(id)?; + (entry.name, FontBook::load(&bytes)?) + }; + // Font changes reset local glyph placements in tune_handwriting. + let local_edits = if id == current { edits.clone() } else { None }; + let mut request = engine.request_with_font( + &draft, + section.clone(), + background.clone(), + local_edits, + primary, + )?; + if request.params.transparent_background { + request.params.transparent_background = false; + data["background_note"] = json!( + "本稿已开启透明 PNG。这里临时显示底纸以比较字体,稿件的 PNG 预览和导出仍使用透明背景。" + ); + } + let rendered = Engine::render_page( + &draft, + section_number, + &request, + photo.as_ref(), + cancel, + page, + ); + let image = match rendered { + Err(error) + if id != current + && error + .downcast_ref::() + .is_some_and(|error| error.code == "invalid_page") => + { + let note = + format!("备选字体 {name} 重新分页后,第 {section_number} 节没有第 {page} 页。"); + unavailable.push(json!({"font":id, "name":name, "section":section_number, + "page":page, "reason":"page_missing_after_reflow", "message":note})); + blocks.push(ContentBlock::text(note)); + continue; + } + other => other + .with_context(|| format!("字体 {name} · 第 {section_number} 节第 {page} 页"))?, + }; + let crop = crop_image(&image, sample.crop)?; + data["native_size"] = json!([image.width(), image.height()]); + data["sample_size"] = json!([crop.width(), crop.height()]); + let mut row = json!({"font":id,"name":name}); + let label = if id == current { + format!("当前字体 · {name}") + } else { + row["tune_arguments"] = json!({ + "draft_id":draft.id, "expected_revision":draft.revision, + "changes":{"font":id}, "preserve_local_adjustments":true + }); + format!("备选字体 · {name}") + }; + blocks.push(ContentBlock::text(label)); + blocks.push(ContentBlock::image( + STANDARD.encode(export::png(&crop)?), + "image/png", + )); + rows.push(row); + } + data["samples"] = json!(rows); + if !unavailable.is_empty() { + data["unavailable_samples"] = json!(unavailable); + } + let notes = ["content_note", "placement_note", "background_note"] + .into_iter() + .filter_map(|key| data[key].as_str()) + .collect::>() + .join("\n"); + let mut result = reply( + format!( + "第 {} 版 · 第 {section_number} 节第 {page} 页。第一张为当前字体。请比较字形、粗细,以及英文和数字是否清楚。若保留当前字体,无需改稿。\n{notes}\n{data}", + draft.revision + ), + data, + ); + result.content.extend(blocks); + Ok(result) +} diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index a80af171..3cd04d75 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -17,6 +17,23 @@ pub struct FontList { pub refresh: bool, /// Set false only to look up an already approved font or its ID when no new style choice is needed. Omit or set true for samples and style choices, even with an exact-name query. pub include_sample_guidance: Option, + /// Instead of searching, render the same saved page in its current font and up to two alternatives. + pub sample: Option, +} + +#[derive(Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FontSample { + pub draft_id: String, + /// Omit for latest. + pub revision: Option, + /// One-based section and page (both default to 1). + pub section: Option, + pub page: Option, + /// One or two candidate IDs from list_fonts. The current font is shown automatically. + pub fonts: Vec, + /// Optional common crop [x,y,width,height] in native output pixels. Frame real mixed text at writing size. + pub crop: Option<[u32; 4]>, } #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)] @@ -53,6 +70,10 @@ pub struct Style { /// Slightly vary letter size and tilt. Defaults on for new homework. Use false for the usual, steadier variation. #[serde(skip_serializing_if = "Option::is_none")] pub relaxed_handwriting: Option, + /// Use the manuscript pen color, opacity, thickness and softness for embedded illustrations. + /// New homework enables this by default. Existing labels inside the image keep their drawn shapes. + #[serde(skip_serializing_if = "Option::is_none")] + pub illustration_uses_pen: Option, /// Keep this value to reproduce handwriting variations. #[schemars(transform = remove_schema_default)] pub seed: u32, @@ -70,6 +91,7 @@ impl Default for Style { font_size: 34, homework: false, relaxed_handwriting: None, + illustration_uses_pen: None, seed: u32::from_le_bytes(Uuid::new_v4().as_bytes()[..4].try_into().unwrap()), } } @@ -127,6 +149,7 @@ impl CreationStyle { if style.homework { // Resolve only on creation: older saved styles keep their original rendering. style.relaxed_handwriting.get_or_insert(true); + style.illustration_uses_pen.get_or_insert(true); } style } @@ -146,6 +169,10 @@ pub struct Save { /// Optional photo-space baselines overriding auto detection on import. Give 2..32 guides, first row 0, last row the last writable line; intermediate guides refine the fit. pub paper_guides: Option>, /// Original Markdown of just this section. A new section starts on a fresh page. + /// For a new labeled diagram use native source, for example: + /// \begin{circuitikz}[flowchart] + /// \draw (0,0) node[rectangle]{B1}; \draw (0,-2) node[diamond]{B2}; + /// \draw[->] (0,0) -- (0,-2); \end{circuitikz} /// Embedded images remain intact in the source. Pages render them as hand-drawn outlines without their original colors. /// If color matters, explain this and offer a preview. Keep the image in the text rather than using it as the paper. pub markdown: String, @@ -295,6 +322,17 @@ pub struct Shape { pub top_width_percent: u8, } +#[derive(Deserialize, Serialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct NaturalLine { + /// Start of the writing baseline in original preview pixels, at the selection's left edge. + pub start: [u32; 2], + /// End of the available baseline, in writing direction. Extra space stays blank. + pub end: [u32; 2], + /// Uniform size relative to the source layout, 50..200 (default 100). Reuse the same value on adjacent rows. + pub scale_percent: Option, +} + #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Nudge { @@ -307,11 +345,18 @@ pub struct Nudge { pub page: usize, /// Up to 32 glyph IDs from preview_handwriting(view="layout") on this page. pub ids: Vec, + /// Move one complete drawing by its native diagram ID or raster illustration parent ID. Use + /// place_center to translate the current outline and all labels together, or target_quad to + /// map the original drawing into exact image corners. Supply only one of these adjustments. + #[serde(default)] + pub whole_drawing: bool, /// For a named text target, send its intended glyph text in ids order (one exact string per ID). A mismatch rejects the whole edit. For repeated text, use nearby words or position to select the occurrence. pub expected_texts: Option>, /// Move this selection as a group so its mean glyph center lands at [x,y] on the preview. Use separately from dx, dy and shape. pub place_center: Option<[u32; 2]>, - /// Image destinations of the original block's TL,TR,BR,BL corners, in that order (for a 90° counterclockwise sidebar: BL,TL,TR,BR of the field). Replaces prior geometry; use separately from other geometry changes. + /// Place one source line along a worksheet baseline, preserving letter proportions, spacing, and baseline offsets in paper space. Use separately from other geometry changes. + pub natural_line: Option, + /// Exact stretch to the original block's TL,TR,BR,BL image destinations (for a 90° counterclockwise sidebar: BL,TL,TR,BR of the field). Use only for intentional four-corner warping. Replaces prior geometry. pub target_quad: Option<[[u32; 2]; 4]>, /// Absolute offsets in pixels from the original glyph position. Omitted fields retain their values. pub dx: Option, @@ -322,6 +367,11 @@ pub struct Nudge { pub angle: Option, /// For text glyphs, a local multiplier of the draft-wide ink opacity, 0..100 percent. 100 adds no fading, 0 hides the glyph. This cannot exceed the global opacity. pub opacity: Option, + /// Optional gradual fade within each selected glyph or diagram. Two [height %, opacity multiplier %] + /// anchors in the unrotated glyph, top to bottom. Both coordinates are 0..100; heights must increase. + /// Values extend beyond the ends. Example [[0,65],[60,100]] preserves the bottom 40%. + /// Multiplies opacity. Pass [[0,100],[100,100]] to clear. + pub opacity_ramp: Option<[[u8; 2]; 2]>, /// Stroke weight delta in pixels, -2..2, in 0.1 px steps. pub thickness: Option, /// Edge softness delta in pixels, -2..2, in 0.1 px steps. @@ -335,6 +385,13 @@ pub struct Nudge { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Preview { + /// In image view, explicitly preview the ZIP PNG finish at the same native dimensions. + /// Gaussian sigma in output pixels (0..2). Use 0 for the original. Add region to see a 1:1 detail. + #[schemars(range(min = 0, max = 2))] + pub export_blur_px: Option, + /// In image view, use instead of export_blur_px for a gradual change of focus. + /// Anchors are relative to the full output, including when requesting a native crop. + pub export_blur_gradient: Option, /// In review, compare with an earlier revision. Omit region for stored, data-only evidence (offset/limit paginate edits). With region, render paired crops. pub compare_revision: Option, /// Pin the earlier stored full-page check by ID. Requires view=review and compare_revision, without a region. The check must belong to that earlier revision, draft, section and page. @@ -345,6 +402,8 @@ pub struct Preview { pub previous_region: Option>, /// In layout view, only return raster illustration outlines and isolated details. Omit for generated circuitikz: its labels and lines are one glyph. pub illustrations_only: Option, + /// Layout: whole drawings only, including native diagrams and raster illustration roots. + pub drawings_only: Option, /// "image" (default), "paper" for saved stationery, "layout" for glyph geometry, or "review" for appearance evidence. /// For a hand-drawn diagram, compare its lines with nearby writing in a small review region at the same zoom. pub view: Option, @@ -369,6 +428,12 @@ pub struct Export { pub revision: Option, /// PDF includes the paper. ZIP contains page PNGs and respects the transparent_background ink control. pub format: Option, + /// ZIP only. Gaussian blur sigma in original image pixels, 0..2 (default 0). Softens the whole finished page, including photographed paper, for this export only. + #[schemars(range(min = 0, max = 2))] + pub export_blur_px: Option, + /// ZIP PNGs: two focus anchors on the full page, with normalized x/y (0..1) and sigma_px (0..2). + /// Use instead of export_blur_px. Strength varies along the line and holds constant past each end. + pub export_blur_gradient: Option, /// Include the exported bytes as an embedded MCP resource for clients that can offer attachments. /// Up to 512 KiB before base64 encoding. Larger files stay available at the returned server path. #[serde(default)] diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 7717399e..7b46453c 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -40,6 +40,7 @@ struct State { drafts: Drafts, preserve_reviews: bool, engine: Mutex, + paper_focus: paper::focus::Cache, fonts: Vec, local_fonts: LocalFonts, storage: storage::Storage, @@ -279,9 +280,9 @@ impl ServerHandler for Panache { "If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ", "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", "For a school assignment, even text alone, set style.homework=true on creation; omit font unless the user specifies one. For further variation (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ", - "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. When the user wants to compare fonts, see list_fonts for sample guidance. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ", + "English letters and digits follow the main font by default. Leave Latin controls unset unless the user requests a different look for them or dislikes how they appear. For a font comparison, show the labeled images from list_fonts(sample=...) on the actual draft paper and mixed text. A paper_path must be readable on the server computer. For a chat photo, use client transfer or run Panache on the computer with the photo. Ask for the missing file only if needed. ", "For print-and-report, export once and report review.unreviewed_pages. Look up existing receipts with read_section(view=review); full-page preview_handwriting(view=review) files a check. Last-page lookups use current pagination and cannot confirm the historical last page. Follow photo_appearance.preview_arguments for a native detail crop. ", - "If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", + "For a new labeled flowchart, use the native [flowchart] example in save_section.markdown so its lettering follows the selected font. For diagrams or icons on a paper photo, inspect diagram_perspective_check in the page review at the final position. Compare both horizontal edges and both side directions, near/far widths and nearby writing against the actual paper. Projection already covers the complete drawing. If it matches, retain it. If only this drawing differs and four actual reference corners can be located, apply target_quad with whole_drawing=true and verify the labels and arrows together. For uploaded sheets, follow paper_focus_check on import and preview. Compare nearby printed edges with added strokes in the sharper, transition and softer areas at native size before export. If a mismatch is visible, adjust only the affected writing or diagram, then recheck the transition and the sharper area. At native size compare local_paper_ink_check for the first written row with nearby photographed marks. If the top looks too dark, taper local opacity into the body and recheck. Use opacity_ramp within a tall drawing that crosses the transition. For a plain PNG export leave blur unset. For a lightly softened PNG with no direction specified, start with uniform export_blur_px=0.6. For a photographed worksheet PNG, after local edits check whether review supplies png_finish_comparison. If it does, compare its clear and gradient native crops at both locations before choosing. Keep the clear finish when both fit or delicate writing fades. When focus should vary across the photograph, use export_blur_gradient instead. Position its two anchors from the request or inspected photo. Preview the same revision at both ends and in between with view=image and region, then export ZIP using the same finish. If images cannot reach the model, use the reported measurements and ask the user to inspect the page before judging its appearance. ", "Forms, unruled paper and artwork are supported. Follow specified or delegated placement, matching field orientation and preserving printed labels. ", "If the intended writing area is ambiguous, ask which field to fill or leave clear. ", "Photo coordinates use native output pixels; local dx/dy use paper-space pixels. ", @@ -332,13 +333,7 @@ impl Panache { let mut effective = serde_json::Map::new(); for k in data["controls"].as_object().unwrap().keys() { let val = match k.as_str() { - "font" => json!( - draft - .controls - .get(k) - .and_then(|v| v.as_str()) - .unwrap_or(&draft.style.font) - ), + "font" => json!(draft.font_name()), "paper" => draft .controls .get(k) @@ -389,9 +384,29 @@ impl Panache { #[tool( annotations(read_only_hint = true, open_world_hint = false), - 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." + description = "Search bundled, personal and system fonts. To compare fonts on the saved paper, pass sample with draft_id, one or two candidate IDs and an optional native-pixel crop. The current image retains local edits. Candidates reflow, so check which words occupy the same region. Samples show the paper even for transparent PNG drafts. Returns labeled images and tune_handwriting arguments without editing the draft." )] - async fn list_fonts(&self, Parameters(input): Parameters) -> CallToolResult { + async fn list_fonts( + &self, + Parameters(input): Parameters, + ctx: RequestContext, + ) -> CallToolResult { + if let Some(sample) = input.sample { + return tool_result( + self.render(ctx, move |state, engine, cancel| { + ensure!( + input.query.is_empty() + && input.source.is_none() + && input.offset == 0 + && input.limit.is_none() + && !input.refresh, + "Use catalog search fields separately from sample" + ); + engine::font_samples::compare(state, engine, sample, cancel) + }) + .await, + ); + } let include_sample_guidance = input.include_sample_guidance.unwrap_or(true); let query = FontSearch { query: input.query, @@ -407,9 +422,9 @@ impl Panache { 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. ", + "Save the actual paper, settings and task text first. Call list_fonts(sample={draft_id,fonts:[candidate_id]}) for labeled images of the same page, optionally adding crop:[x,y,width,height] around a mixed line. 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. ", - "Keep an approved font. For a less regular hand inspect describe_controls(group=variation) and preview a small change. If the user wants occasional corrections, inspect group=strike. 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)." + "Keep an approved font, or apply the chosen candidate's tune_arguments once. Render diagram labels with that same draft font. For a less regular hand inspect describe_controls(group=variation) and preview a small change. If the user wants occasional corrections, inspect group=strike. 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, @@ -430,7 +445,7 @@ impl Panache { } #[tool( - description = "Create a draft from text or a problem supplied in chat. To show its first page, save first, then preview. Saves Markdown without rendering. For schoolwork with or without a photo, set style.homework=true. For a local text change try replace_section_text first to check saved placements. For pen-matched flowcharts, use a circuitikz environment with \\draw[->] paths and node labels. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment." + description = "Create a draft from text or a problem supplied in chat. To show its first page, save first, then preview. Saves Markdown without rendering. For schoolwork with or without a photo, set style.homework=true. For a local text change try replace_section_text first to check saved placements. For new flowcharts use \\begin{circuitikz}[flowchart] with node[rectangle], node[diamond] or node[circle] and \\draw[->] connections. The labels and outlines use the manuscript pen. Keep the diagram at natural scale. On a photo inspect diagram_perspective_check: compare its whole frame and labels with the local paper plane, both across and down the sheet, as well as their pen weight. On creation, optionally import a local stationery image with paper_path. Append or revise a section with expected_revision. Each section starts a new page. Keep the returned draft_id and revision. Returns detected paper.alignment." )] async fn save_section(&self, Parameters(input): Parameters) -> CallToolResult { tool_result(save::run(self, input).await) @@ -534,7 +549,7 @@ impl Panache { #[tool( annotations(open_world_hint = false), - description = "Use view=image to see the page without filing a check. A full-page view=review without compare_revision renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. With compare_revision and no region it reads stored data, review IDs, intervening edits and limitations. Add before_review_id to pin the earlier stored check for that draft, revision, section and page. With region it rerenders labeled crops in the current environment using native image coordinates and measures visible changes. The crops do not contain archived pixels. Add compare_revision for paired before/after and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers. illustrations_only selects raster illustrations, not generated circuitikz. Locate a circuit on the current image, then query its region at the same revision without that filter for the whole diagram ID. Edit its Markdown to change a label. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." + description = "Use view=image to see the page without filing a check. A full-page view=review without compare_revision renders and records a check. To look up an existing check without rendering use read_section(view=review, section, page). view=review returns paper, finished appearance, overlay and full-page evidence. For a diagram on photographed paper, open diagram_perspective_check in review to compare the current four corners with the local paper axes. Its layout_arguments identify the whole drawing. For photo ink, inspect local_paper_ink_check beside nearby paper marks and paper_focus_check for edge changes. In image view set export_blur_px for uniform softness or export_blur_gradient for two full-page focus anchors. Use the same finish for ZIP. Add region for a 1:1 crop. Open the supplied crop arguments at native size before adjusting softness. With compare_revision and no region it reads stored data, review IDs, intervening edits and limitations. Add before_review_id to pin the earlier stored check for that draft, revision, section and page. With region it rerenders labeled crops in the current environment using native image coordinates and measures visible changes. The crops do not contain archived pixels. Add compare_revision for paired before/after and previous_region for the old location of moved content. Use a separate region to inspect protected content. view=layout returns glyph IDs and base boxes [x,y,width,height], paginated by offset/limit. Use region to select current glyph centers. drawings_only selects native diagrams and whole raster drawings. illustrations_only selects raster units including independently editable details. Edit its Markdown to change a label. Projected layouts include base photo_quad (TL,TR,BR,BL) and photo_baseline. view=paper returns the saved background." )] async fn preview_handwriting( &self, @@ -562,7 +577,7 @@ impl Panache { } #[tool( - description = "Adjust selected glyphs in one section/page by IDs from its layout view. Use the same revision. Offsets and shape are in paper space before sheet projection. Use place_center for a group move; target_quad maps the entire selected text block into four corners on the image. Shape adjusts each glyph individually. An ID is local to the exact layout revision, section and page that returned it. After an intervening edit, read the latest layout and resolve the intended glyph again; do not reuse old IDs by changing only expected_revision." + description = "Adjust selected glyphs by IDs from this section/page's layout at the same revision. For worksheet lettering use natural_line with two image points on the writing baseline. It preserves original letter proportions and spacing in paper space, replaces prior warps, and leaves unused row width blank. Use one uniform size across related rows. For an entire diagram on a photo, inspect diagram_perspective_check first. Use whole_drawing=true with its single root ID and place_center to translate all parts, or target_quad when four measured corners require a correction. Use target_quad only for an intentional exact four-corner warp. Offsets and per-glyph shape are in paper space. After an intervening edit, read the latest layout and locate the intended glyph again; do not reuse old IDs by changing only expected_revision." )] async fn adjust_glyphs( &self, @@ -583,11 +598,15 @@ impl Panache { input.note.as_ref().is_none_or(|s| s.chars().count() <= 320), "Note exceeds 320 characters" ); - let next = engine.adjust(&draft, section, &input, cancel)?; - Ok(reply( - format!("Saved revision {next}."), - json!({"draft_id":draft.id,"revision":next,"count":input.ids.len()}), - )) + let (next, placement, count) = engine.adjust(&draft, section, &input, cancel)?; + let mut message = format!("Saved revision {next}."); + let mut data = json!({"draft_id":draft.id,"revision":next,"count":count}); + if let Some(report) = placement { + message.push(' '); + message.push_str(&report.summary()); + data["placement"] = json!(report); + } + Ok(reply(message, data)) }) .await, ) @@ -625,7 +644,7 @@ impl Panache { } #[tool( - description = "Export a revision in section order as PDF (default, includes paper) or ZIP of PNGs. Return the path, page count and review.unreviewed_pages for print-and-report. To look up a listed page use read_section(view=review); only a requested new check needs preview_handwriting(view=review) at the exported revision. For transparent PNGs set transparent_background=true in the ink group before exporting ZIP. For clients that can receive embedded files, request include_file. An embedded resource URI is not a user-visible download URL. The returned path is local to the computer running Panache. With only this path, tell the user in their language: 'On the computer running Panache, open this file: '. Put the path in inline code, never in a download link. If the chat host confirms a visible attachment, point to that attachment instead; if its receipt gives a download URL, include that exact URL in the final reply." + description = "Export a revision in section order as PDF (default, includes paper) or ZIP of PNGs. Return the path, page count and review.unreviewed_pages for print-and-report. To look up a listed page use read_section(view=review); only a requested new check needs preview_handwriting(view=review) at the exported revision. ZIP supports uniform export_blur_px or directional export_blur_gradient as shown in preview_handwriting. For transparent PNGs set transparent_background=true in the ink group before exporting ZIP. For clients that can receive embedded files, request include_file. An embedded resource URI is not a user-visible download URL. The returned path is local to the computer running Panache. With only this path, tell the user in their language: 'On the computer running Panache, open this file: '. Put the path in inline code, never in a download link. If the chat host confirms a visible attachment, point to that attachment instead; if its receipt gives a download URL, include that exact URL in the final reply." )] async fn export_handwriting( &self, @@ -635,6 +654,10 @@ impl Panache { let progress_token = ctx.meta.get_progress_token(); let peer = ctx.peer.clone(); let result = self.render(ctx, move |state, engine, cancel| { + let format = input.format.unwrap_or_default(); + let finish = engine::export_blur::finish(input.export_blur_px, input.export_blur_gradient)?; + let active_finish = finish.filter(|f| f.active()); + ensure!(matches!(format, Format::Zip) || active_finish.is_none(), "Nonzero PNG blur requires format=zip. For PDF, omit the blur settings or use zero strength."); let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; let sections = state.drafts.sections(&input.draft_id, draft.revision, None)?; let reviewed_pages = draft.reviewed_pages()?; @@ -644,9 +667,8 @@ impl Panache { let mut different = Vec::new(); let params = controls::parameters(&draft, 1, &draft.controls)?; let zero_text_ink = params.ink_opacity == 0 || params.fill[3] == 0; - let format = input.format.unwrap_or_default(); let (path, pages, file) = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export( - writer, &draft, sections, format, cancel, + writer, &draft, sections, (format, active_finish), cancel, |pages, section, page, image| { match reviewed_pages.get(&(section, page)) { Some(record) => { @@ -694,21 +716,32 @@ impl Panache { if matches!(format, Format::Zip) { let without_digest = reviewed - matching - different.len(); if !different.is_empty() { - pixel_warning = format!(" ZIP 中这些页的像素与该版最近一次整页检查单不一致:{}。", serde_json::to_string(&different)?); + let stage = if active_finish.is_some() { "柔化前" } else { "ZIP 中" }; + pixel_warning = format!(" {stage}这些页的像素与该版最近一次整页检查单不一致:{}。", serde_json::to_string(&different)?); } if without_digest > 0 { pixel_warning.push_str(&format!(" {without_digest} 页的检查单没有像素摘要,无法比对。")); } - review["zip_pixels"] = json!({ + let comparison = json!({ "pages_matching_latest_review": matching, "different_pages": different, "reviewed_pages_without_digest": without_digest, }); + review["zip_pixels"] = if let Some(finish) = active_finish { + let mut evidence = json!({"status":"not_compared_after_export_blur","before_blur":comparison}); + finish.write_metadata(&mut evidence); + pixel_warning.push_str(" 此次导出的 PNG 已按所选参数柔化。检查单的像素摘要对应柔化前的页面。"); + evidence + } else { comparison }; } let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}{pixel_warning}\n\n运行 Panache 的电脑上的文件:`{}`", draft.revision, path.display()); - let mut result = reply(message, json!({ + let mut metadata = json!({ "draft_id": input.draft_id, "revision": draft.revision, "path": path, "pages": pages, "review": review, - })); + }); + if matches!(format, Format::Zip) && let Some(finish @ engine::export_blur::Finish::Gradient(_)) = finish { + finish.write_metadata(&mut metadata); + } + let mut result = reply(message, metadata); if input.include_file { delivery::include_file(&mut result, file, &path, format); } @@ -771,6 +804,7 @@ async fn main() -> Result<()> { .with_bundled_dir(font_dir), fonts: engine.names.clone(), engine: Mutex::new(engine), + paper_focus: Default::default(), worker: fs::read_to_string(worker)?.into(), render_slot: Arc::new(Semaphore::new(1)), prepare_slot: Arc::new(Semaphore::new(1)), diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index 0640547c..3a2fafae 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -1,3 +1,5 @@ +pub mod focus; + use crate::{Guide, PaperMode}; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; @@ -144,6 +146,7 @@ impl PaperLayout { pub struct ImportedPaper { pub layout: PaperLayout, + pub focus: focus::Profile, pub bytes: Vec, } @@ -168,6 +171,7 @@ impl ImportedPaper { file.take(limits.max_file_bytes as u64 + 1) .read_to_end(&mut bytes)?; let image = imaging::decode(&bytes, &limits)?; + let mut corrected_background = false; let layout = if let Some(guides) = guides { ensure!(mode == PaperMode::Photo, "paper_guides require photo mode"); PaperLayout::from_guides(image.width(), image.height(), guides)? @@ -181,6 +185,7 @@ impl ImportedPaper { if mode == PaperMode::Flatten { if let Some(corrected) = lines.corrected_background.take() { bytes = STANDARD.decode(corrected)?; + corrected_background = true; ensure!( bytes.len() <= limits.max_file_bytes, "Aligned paper exceeds the file size limit" @@ -227,6 +232,15 @@ impl ImportedPaper { }; layout.apply(&mut params); params.validate(layout.width, layout.height, &limits)?; - Ok(Self { layout, bytes }) + let focus = if corrected_background { + focus::measure(&imaging::decode(&bytes, &limits)?) + } else { + focus::measure(&image) + }; + Ok(Self { + layout, + bytes, + focus, + }) } } diff --git a/crates/panache-mcp/src/paper/focus.rs b/crates/panache-mcp/src/paper/focus.rs new file mode 100644 index 00000000..9967972a --- /dev/null +++ b/crates/panache-mcp/src/paper/focus.rs @@ -0,0 +1,547 @@ +//! Sample the spread of repeatable dark printed edges on the untouched paper. +use crate::drafts::Snapshot; +use anyhow::Result; +use handwriting_core::{Limits, imaging}; +use image::{GenericImageView, Pixel, Rgba}; +use serde_json::{Value, json}; +use std::{collections::VecDeque, sync::Mutex}; + +const GRID: u32 = 4; +const TRACKS: u32 = 9; +const WINDOW: u32 = 240; + +#[derive(Clone, Copy)] +struct Edge { + at: usize, + contrast: i16, + width: f32, +} + +pub(crate) fn luma(pixel: Rgba) -> i16 { + let opacity = u16::from(pixel[3]); + (255 - ((255 - u16::from(pixel.to_luma()[0])) * opacity).div_ceil(255)) as i16 +} + +// Track the 20% and 80% crossings of a monotone edge relative to its own local contrast. +// Parallel profiles 2 px to either side reject isolated grain. Give diagonal edges to their +// stronger scan direction and correct the width of that projection. +pub(crate) struct PaperStroke { + pub at: usize, + pub width: f32, + pub contrast: u8, + pub darkest_at: usize, +} + +pub(crate) fn stroke_edges( + profile: &[[i16; 3]], + min_contrast: i16, + min_slope: i16, +) -> Vec { + let mut out = Vec::new(); + let mut descending: Option = None; + let mut i = 0; + while i + 1 < profile.len() { + let sign = (profile[i + 1][1] - profile[i][1]).signum(); + if sign == 0 { + i += 1; + continue; + } + let start = i; + let mut peak = i; + let mut slope = 0; + while i + 1 < profile.len() { + let d = sign * (profile[i + 1][1] - profile[i][1]); + if d <= 0 { + break; + } + if d > slope { + peak = i; + slope = d; + } + i += 1; + } + let contrast = sign * (profile[i][1] - profile[start][1]); + if contrast < min_contrast + || slope < min_slope + || i - start > 22 + || start < 2 + || i + 2 >= profile.len() + { + continue; + } + let transverse = (profile[peak][2] + profile[peak + 1][2] + - profile[peak][0] + - profile[peak + 1][0]) as f32 + / 8.; + if transverse.abs() > f32::from(slope) { + continue; + } + let coherent = [0, 2].into_iter().all(|j| { + (-2isize..=2).any(|shift| { + let a = (start as isize + shift) as usize; + let b = (i as isize + shift) as usize; + let d = sign * (profile[b][j] - profile[a][j]); + d * 2 >= contrast && d <= contrast * 2 + }) + }); + if !coherent { + continue; + } + let crossing = |fraction: f32| { + let level = f32::from(contrast) * fraction; + let mut k = start; + while k + 1 < i && f32::from(sign * (profile[k + 1][1] - profile[start][1])) < level { + k += 1; + } + k as f32 + + (level - f32::from(sign * (profile[k][1] - profile[start][1]))) + / f32::from(sign * (profile[k + 1][1] - profile[k][1])) + }; + let width = + (crossing(0.8) - crossing(0.2)) * f32::from(slope) / f32::from(slope).hypot(transverse); + let edge = Edge { + at: peak, + contrast, + width, + }; + if sign < 0 { + descending = Some(edge); + } else if let Some(other) = descending.take() + && edge.at - other.at <= 36 + && edge.contrast.min(other.contrast) * 2 >= edge.contrast.max(other.contrast) + { + out.push(PaperStroke { + at: other.at, + width: (other.width + edge.width) / 2., + contrast: other.contrast.min(edge.contrast) as u8, + darkest_at: (other.at..=edge.at + 1) + .min_by_key(|&k| profile[k][1]) + .unwrap(), + }); + } + } + out +} + +#[derive(Clone, Copy)] +struct Sample { + point: [u32; 2], + cell: [u32; 2], + horizontal_scan: bool, + width: f32, + strokes: usize, + tracks: usize, +} + +fn sample_cell( + img: &impl GenericImageView>, + cell: [u32; 2], + horizontal: bool, +) -> Option { + let [w, h] = [img.width(), img.height()]; + let axis = |v: [u32; 2]| if horizontal { v } else { [v[1], v[0]] }; + let [along, across] = axis([w, h]); + let [a, b] = axis(cell); + let start = along * a / GRID; + let end = along * (a + 1) / GRID; + let lo = across * b / GRID; + let hi = across * (b + 1) / GRID; + if end - start < 20 || hi - lo < 8 { + return None; + } + let windows = (end - start).div_ceil(WINDOW).min(3); + let length = (end - start) / windows; + let count = (hi - lo - 4).min(TRACKS); + let mut samples = Vec::new(); + let mut supported = 0; + for track in 0..count { + let cross = lo + 2 + (2 * track + 1) * (hi - lo - 4) / (2 * count); + let old = samples.len(); + for window in 0..windows { + let size = length.min(WINDOW); + let from = start + window * length + (length - size) / 2; + let profile: Vec<_> = (from..from + size) + .map(|x| { + [cross - 2, cross, cross + 2].map(|y| { + let [x, y] = axis([x, y]); + luma(img.get_pixel(x, y)) + }) + }) + .collect(); + for stroke in stroke_edges(&profile, 22, 4) { + samples.push((stroke.width, axis([from + stroke.at as u32, cross]))); + } + } + supported += usize::from(samples.len() > old); + } + if samples.len() < 6 || supported < 3 { + return None; + } + samples.sort_unstable_by(|a, b| a.0.total_cmp(&b.0)); + let (width, point) = samples[samples.len() / 2]; + Some(Sample { + point, + cell, + horizontal_scan: horizontal, + width, + strokes: samples.len(), + tracks: supported, + }) +} + +#[derive(Clone, Default)] +pub struct Profile { + size: [u32; 2], + samples: Vec, +} + +pub fn measure(img: &impl GenericImageView>) -> Profile { + let mut profile = Profile { + size: [img.width(), img.height()], + samples: Vec::new(), + }; + for y in 0..GRID { + for x in 0..GRID { + for horizontal in [true, false] { + if let Some(s) = sample_cell(img, [x, y], horizontal) { + profile.samples.push(s); + } + } + } + } + profile +} + +impl Profile { + pub fn report( + &self, + draft: &str, + revision: u32, + section: u32, + page: usize, + compare_finish: bool, + ) -> Value { + let [w, h] = self.size; + let crop = |[x, y]: [u32; 2]| { + let cw = w.min(240); + let ch = h.min(160); + let l = x.saturating_sub(cw / 2).min(w - cw); + let t = y.saturating_sub(ch / 2).min(h - ch); + json!({"draft_id":draft,"revision":revision,"section":section,"page":page,"view":"review", + "region":[[l,t],[l+cw,t],[l+cw,t+ch],[l,t+ch]]}) + }; + let site = |role: &str, s: &Sample| { + json!({"role":role,"sample_point":s.point,"median_edge_width_px":s.width,"sampled_strokes":s.strokes, + "supported_tracks":s.tracks,"scan_direction":if s.horizontal_scan {"horizontal"} else {"vertical"}, + "preview_arguments":crop(s.point)}) + }; + let mut cells = [false; 16]; + for s in &self.samples { + cells[(s.cell[1] * GRID + s.cell[0]) as usize] = true; + } + let coverage = cells.iter().filter(|v| **v).count(); + let mut largest = None; + let mut references = None; + for a in &self.samples { + for b in &self.samples { + let difference = b.width - a.width; + if a.horizontal_scan != b.horizontal_scan || a.cell == b.cell || difference < 0. { + continue; + } + if references.is_none_or(|(d, _, _)| difference > d) { + references = Some((difference, a, b)); + } + if b.width >= 2.0 + && difference >= 1.1 + && b.width >= 1.65 * a.width + && largest.is_none_or(|(d, _, _)| difference > d) + { + largest = Some((difference, a, b)); + } + } + } + let mut regions = Vec::new(); + let status = if let Some((_, a, b)) = largest { + regions.push(site("narrower_edges", a)); + regions.push(site("broader_edges", b)); + let mid = [(a.point[0] + b.point[0]) / 2, (a.point[1] + b.point[1]) / 2]; + let between = self + .samples + .iter() + .filter(|s| { + s.horizontal_scan == a.horizontal_scan + && s.cell != a.cell + && s.cell != b.cell + && s.width > a.width + 0.25 + && s.width < b.width - 0.25 + && (0..2).all(|k| { + (a.cell[k].min(b.cell[k])..=a.cell[k].max(b.cell[k])) + .contains(&s.cell[k]) + }) + }) + .min_by_key(|s| { + (0..2) + .map(|k| u64::from(s.point[k].abs_diff(mid[k])).pow(2)) + .sum::() + }); + regions.push(between.map_or_else( + || json!({"role":"between_samples","preview_arguments":crop(mid)}), + |s| site("intermediate_edges", s), + )); + "spatial_variation" + } else if let Some(broadest) = self + .samples + .iter() + .max_by(|a, b| a.width.total_cmp(&b.width)) + { + if let Some((_, a, b)) = references { + regions.push(site("narrower_reference", a)); + regions.push(site("broader_reference", b)); + } else { + regions.push(site("paper_edge_sample", broadest)); + } + let broad = self.samples.iter().all(|s| s.width >= 2.); + let spread = (0..GRID).all(|k| { + self.samples.iter().any(|s| s.cell[0] == k) + && self.samples.iter().any(|s| s.cell[1] == k) + }); + if broad && coverage >= 8 && spread { + "broad_edges_across_sheet" + } else if broadest.width >= 2. { + "broad_edges_in_samples" + } else { + "no_clear_softening_in_samples" + } + } else { + regions.push(json!({"role":"inspect_paper","preview_arguments":crop([w/2,h/2])})); + "insufficient_edge_support" + }; + let guidance = match status { + "spatial_variation" => { + "底纸不同位置的深色印刷边缘过渡宽度有差异。按区域参数用原尺寸从较清晰处经过交界到较软处,对照当地纸上细线、图形轮廓、图内标签和正文。between_samples 是待核对点。" + } + "broad_edges_across_sheet" | "broad_edges_in_samples" => { + "受支持的底纸样本有较宽的边缘过渡。按区域参数检查原尺寸印迹,比较各处图线、标签和正文与当地纸边。" + } + "insufficient_edge_support" => { + "底纸上可重复测量的深色边缘不足。用原尺寸检查原纸上的细线或印字,尤其留意用户标注的位置。" + } + _ => { + "采样差异未达显著门槛。有同向可比样本时,参考裁区给出较窄与较宽的实测边缘。缓慢渐变和很小的软区可能遗漏。沿同一条纸上印线或同类印字连续检查相邻区域,用原尺寸对照图线、图内标签和正文。" + } + }; + let mut report = json!({"status":status,"supported_cells":coverage,"grid":[GRID,GRID],"regions":regions,"guidance":guidance, + "local_edit_guidance":"优先检查用户指明的位置,可平移 region 连续查看过渡,保留原纸与清晰区。仅在裁图或用户反馈支持时,对可独立选择的字或图块分区小调 softness 后复看。若布局只给流程图及其标签一个字形 ID,softness 会影响整张图;需要只改某一部分应在可局部修改的图源中处理。", + "method":"Native 20–80% lightness transition width on opposing, locally contrasted stroke edges, confirmed by parallel profiles. Comparisons use the same scan direction. Print, material and capture can all broaden an edge."}); + // 2026-11-27:半像素差只用于提供可逆的对照预览,不改变纸面焦差检测结论。 + if compare_finish + && let Some((delta, sharp, soft)) = largest.or(references) + && delta >= 0.5 + && sharp.point != soft.point + && w > 1 + && h > 1 + { + let anchor = |s: &Sample, sigma: f64| { + json!({ + "x":f64::from(s.point[0])/f64::from(w-1), + "y":f64::from(s.point[1])/f64::from(h-1), + "sigma_px":sigma + }) + }; + let gradient = json!({"from":anchor(soft,0.8),"to":anchor(sharp,0.)}); + let pair = |point| { + let mut clear = crop(point); + clear["view"] = json!("image"); + let mut candidate = clear.clone(); + clear["export_blur_px"] = json!(0); + candidate["export_blur_gradient"] = gradient.clone(); + json!({"clear":clear,"gradient":candidate}) + }; + report["png_finish_comparison"] = json!({ + "guidance":"照片 PNG 定稿前,若原尺寸观察也显示一侧较软,先比较本版两处裁图。分别把 softer_area 和 sharper_area 中的 clear、gradient 参数传给 preview_handwriting,比较同一位置的纸面细线与笔画。参考框缺少字迹时,两档的 region 一起移到附近的小字,锚点仍按整页。0.8→0 是试看的强度;边缘宽度也受印刷影响。清晰版已协调、渐变使细字变淡或看不出收益时选清晰版。否则用预览过的同一组渐变参数导出 ZIP。", + "softer_area":pair(soft.point),"sharper_area":pair(sharp.point) + }); + } + report + } +} + +#[derive(Default)] +pub struct Cache(Mutex>); + +impl Cache { + pub fn add_review_guidance( + &self, + draft: &Snapshot<'_>, + section: u32, + page: usize, + transparent: bool, + whole_page: bool, + metadata: &mut Value, + ) -> Result<()> { + if transparent && !whole_page { + return Ok(()); + } + if let Some(mut focus) = self.report(draft, section, page, !transparent)? { + if let Some(trial) = focus + .as_object_mut() + .and_then(|obj| obj.remove("png_finish_comparison")) + { + let hint = "照片 PNG 定稿时,请打开 png_finish_comparison:在同一版的偏软和偏清两处,分别比较 clear 和 gradient 的原尺寸图,再选导出参数。两档都协调或渐变损失细笔时选清晰版。"; + let previous = metadata["next_step"].as_str().unwrap_or_default(); + metadata["next_step"] = json!(format!("{previous} {hint}").trim()); + if let Some(appearance) = metadata.get_mut("photo_appearance") { + appearance["png_finish_guidance"] = json!(hint); + } + metadata["png_finish_comparison"] = trial; + } + if whole_page { + metadata["paper_focus_check"] = focus; + } + } + Ok(()) + } + + pub fn remember(&self, id: &str, profile: Profile) { + let mut entries = self.0.lock().unwrap_or_else(|e| e.into_inner()); + entries.retain(|e| e.0 != id); + entries.push_back((id.to_owned(), profile)); + if entries.len() > 32 { + entries.pop_front(); + } + } + + pub fn report( + &self, + draft: &Snapshot<'_>, + section: u32, + page: usize, + compare_finish: bool, + ) -> Result> { + if draft.paper.is_none() { + return Ok(None); + } + let profile = self + .0 + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .find(|e| e.0 == draft.id) + .map(|e| e.1.clone()); + let profile = match profile { + Some(v) => v, + None => { + let Some(bytes) = draft.background()? else { + return Ok(None); + }; + let v = measure(&imaging::decode(&bytes, &Limits::default())?); + self.remember(draft.id, v.clone()); + v + } + }; + Ok(Some(profile.report( + draft.id, + draft.revision, + section, + page, + compare_finish, + ))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{DynamicImage, GrayImage, Luma, imageops}; + + fn rulings(vertical: bool, contrast: u8) -> GrayImage { + GrayImage::from_fn(480, 480, |x, y| { + let line = if vertical { x } else { y }; + Luma([if (line % 22) < 6 { 238 - contrast } else { 238 }]) + }) + } + + fn report(img: GrayImage) -> Value { + measure(&DynamicImage::ImageLuma8(img)).report("draft", 2, 3, 4, true) + } + + #[test] + fn widths_follow_blur_in_either_direction_without_equating_ink_contrast_to_focus() { + for vertical in [true, false] { + let lines = rulings(vertical, 160); + let soft = imageops::blur(&lines, 2.); + let medium = imageops::blur(&lines, 1.1); + let original = report(lines.clone()); + assert_eq!(original["status"], "no_clear_softening_in_samples"); + assert_eq!(original["regions"][0]["role"], "narrower_reference"); + assert!(original.get("png_finish_comparison").is_none()); + assert_eq!(original["regions"][1]["role"], "broader_reference"); + assert_eq!( + original["regions"][0]["scan_direction"], + original["regions"][1]["scan_direction"] + ); + assert_ne!( + original["regions"][0]["sample_point"], + original["regions"][1]["sample_point"] + ); + assert_eq!(report(soft.clone())["status"], "broad_edges_across_sheet"); + let stages = GrayImage::from_fn(480, 480, |x, y| { + *[&lines, &medium, &medium, &soft][x as usize / 120].get_pixel(x, y) + }); + let result = report(stages); + assert_eq!(result["status"], "spatial_variation", "{result}"); + assert_eq!(result["regions"][2]["role"], "intermediate_edges"); + let thinner = result["regions"][0]["median_edge_width_px"] + .as_f64() + .unwrap(); + let broader = result["regions"][1]["median_edge_width_px"] + .as_f64() + .unwrap(); + assert!(broader > thinner + 1.); + let pale = rulings(vertical, 45); + let colors = + GrayImage::from_fn( + 480, + 480, + |x, y| if x < 240 { lines[(x, y)] } else { pale[(x, y)] }, + ); + assert_eq!(report(colors)["status"], original["status"]); + } + } + + #[test] + fn reversible_trial_can_follow_subthreshold_samples_without_changing_the_detector() { + let sample = |width, x| Sample { + point: [x, 100], + cell: [x / 100, 1], + horizontal_scan: false, + width, + strokes: 32, + tracks: 6, + }; + for (difference, offer) in [(0.49, false), (0.5, true), (0.74, true)] { + let profile = Profile { + size: [400, 300], + samples: vec![sample(1.2, 50), sample(1.2 + difference, 250)], + }; + for review in [false, true] { + let r = profile.report("id", 4, 2, 1, review); + assert_eq!(r["status"], "no_clear_softening_in_samples"); + assert_eq!(r.get("png_finish_comparison").is_some(), review && offer); + } + } + } + + #[test] + fn blank_shadow_and_weak_grain_supply_no_supported_strokes() { + let noisy = GrayImage::from_fn(480, 360, |x, y| { + Luma([(160 + x / 12 + (x.wrapping_mul(y) % 8)) as u8]) + }); + for img in [GrayImage::from_pixel(480, 360, Luma([225])), noisy] { + let r = report(img); + assert_eq!(r["status"], "insufficient_edge_support"); + assert_eq!(r["supported_cells"], 0); + assert!(r.get("png_finish_comparison").is_none()); + } + } +} diff --git a/crates/panache-mcp/src/placement.rs b/crates/panache-mcp/src/placement.rs index 9b69a221..deb2eab4 100644 --- a/crates/panache-mcp/src/placement.rs +++ b/crates/panache-mcp/src/placement.rs @@ -1,30 +1,145 @@ -//! Place a selection's original layout rectangle into four corners on the photograph. -use crate::drafts::Snapshot; +//! Map the original paper-space layout to a baseline or to exact corners on the photograph. +use crate::NaturalLine; use anyhow::{Result, ensure}; use handwriting_core::fine_edit::{Adjustment, GlyphBounds}; +use handwriting_core::photo::PaperProjection; +use serde::Serialize; + +#[derive(Serialize)] +#[serde(tag = "mode", rename_all = "snake_case")] +pub enum PlacementReport { + NaturalLine { + scale_percent: u8, + used_paper_px: f64, + available_paper_px: f64, + }, + TargetQuad { + max_glyph_center_axis_ratio: f64, + }, +} + +impl PlacementReport { + pub fn summary(&self) -> String { + match self { + Self::NaturalLine { + scale_percent, + used_paper_px, + available_paper_px, + } => format!( + "Natural line at {scale_percent}% uniform size uses {used_paper_px:.1} of {available_paper_px:.1} paper pixels." + ), + Self::TargetQuad { + max_glyph_center_axis_ratio: ratio, + } => { + let advice = if *ratio >= 1.15 { + " For proportional lettering along a worksheet row, use natural_line." + } else { + "" + }; + format!( + "Exact four-corner warp. The largest local major/minor scale ratio sampled at glyph centers is {ratio:.2}× in paper space.{advice}" + ) + } + } + } +} + +fn paper_points( + projection: Option<&PaperProjection>, + size: [u32; 2], + points: [[u32; 2]; N], +) -> Result<[[f64; 2]; N]> { + let mut result = [[0.; 2]; N]; + for (dst, src) in result.iter_mut().zip(points) { + ensure!( + src[0] < size[0] && src[1] < size[1], + "Target point outside the image" + ); + let pt = src.map(|v| v as f32); + *dst = projection.map_or(pt, |m| m.paper_point(pt)).map(f64::from); + ensure!( + dst.iter().all(|v| v.is_finite()), + "Invalid paper coordinates" + ); + } + Ok(result) +} + +fn selection_bounds(glyphs: &[GlyphBounds]) -> Result<[f64; 4]> { + let mut left = f64::INFINITY; + let mut top = f64::INFINITY; + let mut right = f64::NEG_INFINITY; + let mut bottom = f64::NEG_INFINITY; + for glyph in glyphs { + let [x, y, w, h] = glyph.bounds.map(f64::from); + left = left.min(x); + top = top.min(y); + right = right.max(x + w); + bottom = bottom.max(y + h); + } + ensure!(right > left && bottom > top, "Empty selection"); + Ok([left, top, right - left, bottom - top]) +} pub struct Placement { - // Paper-space homography normalized at the selection's top left. + // Paper-space homography normalized at the source origin. matrix: [f64; 8], origin: [f64; 2], } impl Placement { - pub fn new( - draft: &Snapshot<'_>, + pub fn natural_line( + projection: Option<&PaperProjection>, + size: [u32; 2], + glyphs: &[GlyphBounds], + line: &NaturalLine, + ) -> Result<(Self, PlacementReport)> { + let [start, end] = paper_points(projection, size, [line.start, line.end])?; + let [left, _, width, _] = selection_bounds(glyphs)?; + let baseline = glyphs[0].baseline; + ensure!( + glyphs.iter().all(|g| g.baseline == baseline + && g.illustration.is_none() + && !g.is_native_diagram), + "Select text on one original layout baseline for natural_line; place each source line separately" + ); + let scale_percent = line.scale_percent.unwrap_or(100); + ensure!( + (50..=200).contains(&scale_percent), + "natural_line scale_percent must be 50..200" + ); + let scale = f64::from(scale_percent) / 100.; + let (dx, dy) = (end[0] - start[0], end[1] - start[1]); + let available = dx.hypot(dy); + ensure!( + available > 0., + "Supply two distinct natural_line baseline points" + ); + let used = width * scale; + ensure!( + used <= available, + "Selection needs {used:.1} paper pixels at {scale_percent}%; only {available:.1} are available. Split the line, extend the baseline, or choose a smaller uniform scale_percent for the worksheet." + ); + let (a, b) = (scale * dx / available, scale * dy / available); + Ok(( + Self { + matrix: [a, -b, start[0], b, a, start[1], 0., 0.], + origin: [left, f64::from(baseline)], + }, + PlacementReport::NaturalLine { + scale_percent, + used_paper_px: used, + available_paper_px: available, + }, + )) + } + + pub fn target_quad( + projection: Option<&PaperProjection>, size: [u32; 2], glyphs: &[GlyphBounds], quad: [[u32; 2]; 4], - ) -> Result { - let mut corners = [[0.; 2]; 4]; - let map = draft.paper.as_ref().and_then(|p| p.projection.as_ref()); - for (dst, src) in corners.iter_mut().zip(quad) { - ensure!( - src[0] < size[0] && src[1] < size[1], - "Target corner outside the image" - ); - let pt = src.map(|v| v as f32); - *dst = map.map_or(pt, |m| m.paper_point(pt)).map(f64::from); - } + ) -> Result<(Self, PlacementReport)> { + let corners = paper_points(projection, size, quad)?; for i in 0..4 { let [a, b, c] = [corners[i], corners[(i + 1) % 4], corners[(i + 2) % 4]]; ensure!( @@ -32,19 +147,7 @@ impl Placement { "Supply a convex TL, TR, BR, BL quadrilateral" ); } - let mut left = f64::INFINITY; - let mut top = f64::INFINITY; - let mut right = f64::NEG_INFINITY; - let mut bottom = f64::NEG_INFINITY; - for g in glyphs { - let [x, y, w, h] = g.bounds.map(f64::from); - left = left.min(x); - top = top.min(y); - right = right.max(x + w); - bottom = bottom.max(y + h); - } - let (w, h) = (right - left, bottom - top); - ensure!(w > 0. && h > 0., "Empty selection"); + let [left, top, w, h] = selection_bounds(glyphs)?; let [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = corners; let (ax, ay) = (x1 - x2, y1 - y2); let (bx, by) = (x3 - x2, y3 - y2); @@ -53,7 +156,7 @@ impl Placement { let det = ax * by - ay * bx; let g = (dx * by - dy * bx) / det; let k = (ax * dy - ay * dx) / det; - Ok(Self { + let placement = Self { origin: [left, top], matrix: [ (x1 * (1. + g) - x0) / w, @@ -65,7 +168,31 @@ impl Placement { g / w, k / h, ], - }) + }; + let mut max_ratio: f64 = 1.; + for glyph in glyphs { + let [x, y, w, h] = glyph.bounds.map(f64::from); + let ratio = placement.axis_ratio_at(x + w / 2. - left, y + h / 2. - top); + ensure!(ratio.is_finite(), "Degenerate perspective at glyph center"); + max_ratio = max_ratio.max(ratio); + } + Ok(( + placement, + PlacementReport::TargetQuad { + max_glyph_center_axis_ratio: max_ratio, + }, + )) + } + + // Singular-value ratio of the local Jacobian. Its common scale cancels. + fn axis_ratio_at(&self, u: f64, v: f64) -> f64 { + let [a, b, c, d, e, f, g, k] = self.matrix; + let z = 1. + g * u + k * v; + let x = (a * u + b * v + c) / z; + let y = (d * u + e * v + f) / z; + let [a, b, d, e] = [a - x * g, b - x * k, d - y * g, e - y * k]; + let major = ((a + e).hypot(d - b) + (a - e).hypot(d + b)) / 2.; + major * major / (a * e - b * d).abs() } pub fn apply(&self, edit: &mut Adjustment, bounds: [i32; 4]) -> Result<()> { @@ -111,3 +238,71 @@ impl Placement { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn glyph(bounds: [i32; 4], id: u32) -> GlyphBounds { + GlyphBounds { + bounds, + id, + baseline: 80, + is_text: true, + is_native_diagram: false, + source_utf16: None, + illustration: None, + } + } + + #[test] + fn natural_line_respects_photo_direction_and_original_baseline_for_inline_math() { + let projection = PaperProjection::Rotated { + angle: std::f32::consts::FRAC_PI_2, + layout_center: [150., 150.], + photo_center: [150., 150.], + }; + let mut glyphs = [glyph([10, 50, 20, 25], 0), glyph([50, 45, 15, 28], 1)]; + glyphs[1].is_text = false; // A formula shares the text baseline. + let line = NaturalLine { + start: [130, 100], + end: [130, 200], + scale_percent: Some(125), + }; + let (placement, report) = + Placement::natural_line(Some(&projection), [300, 300], &glyphs, &line).unwrap(); + assert!( + matches!(report, PlacementReport::NaturalLine { used_paper_px, available_paper_px, .. } + if (used_paper_px - 68.75).abs() < 1e-6 && (available_paper_px - 100.).abs() < 1e-4) + ); + let [a, b, x0, d, e, y0, _, _] = placement.matrix; + for (x, y) in [(10., 80.), (65., 80.), (50., 45.)] { + let (u, v) = (x - placement.origin[0], y - placement.origin[1]); + let [photo_x, photo_y] = + projection.photo_point((a * u + b * v + x0) as f32, (d * u + e * v + y0) as f32); + assert!((f64::from(photo_x) - (130. - 1.25 * (y - 80.))).abs() < 1e-4); + assert!((f64::from(photo_y) - (100. + 1.25 * (x - 10.))).abs() < 1e-4); + } + glyphs[1].illustration = Some(1); + assert!(Placement::natural_line(Some(&projection), [300, 300], &glyphs, &line).is_err()); + } + + #[test] + fn exact_quad_keeps_illustrations_and_measures_shear_even_with_equal_edge_lengths() { + let mut glyph = glyph([0, 0, 10, 10], 0); + glyph.is_text = false; + glyph.illustration = Some(0); + // Both destination axes have length 5 but their angle is no longer 90°. + let (_, report) = Placement::target_quad( + None, + [30, 30], + &[glyph], + [[10, 10], [15, 10], [18, 14], [13, 14]], + ) + .unwrap(); + assert!( + matches!(report, PlacementReport::TargetQuad { max_glyph_center_axis_ratio } + if (max_glyph_center_axis_ratio - 2.).abs() < 1e-10) + ); + } +} diff --git a/crates/panache-mcp/src/preview.rs b/crates/panache-mcp/src/preview.rs index 3ef171be..d582b8e4 100644 --- a/crates/panache-mcp/src/preview.rs +++ b/crates/panache-mcp/src/preview.rs @@ -1,12 +1,12 @@ use crate::{ Panache, Preview, PreviewView, State, drafts::{Section, Snapshot}, - engine::Engine, + engine::{Engine, export_blur}, reply, review, }; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; -use handwriting_core::{Cancellation, Limits}; +use handwriting_core::{Cancellation, Limits, export}; use rmcp::{ RoleServer, model::{CallToolResult, ContentBlock}, @@ -19,6 +19,13 @@ pub(super) async fn run( input: Preview, ctx: RequestContext, ) -> Result { + let finish = export_blur::finish(input.export_blur_px, input.export_blur_gradient)?; + if finish.is_some() { + ensure!( + matches!(input.view, None | Some(PreviewView::Image)), + "export_blur_px and export_blur_gradient require view=image" + ); + } ensure!( !input.fresh || matches!(input.view, None | Some(PreviewView::Image)), "fresh=true requires view=image (or no view)" @@ -29,7 +36,8 @@ pub(super) async fn run( && input.compare_revision.is_some() && input.region.is_none() && input.previous_region.is_none() - && input.illustrations_only.is_none()), + && input.illustrations_only.is_none() + && input.drawings_only.is_none()), "before_review_id requires an unfiltered view=review with compare_revision and no region" ); ensure!( @@ -43,7 +51,9 @@ pub(super) async fn run( && input.region.is_none() { ensure!( - input.view == Some(PreviewView::Review) && input.illustrations_only.is_none(), + input.view == Some(PreviewView::Review) + && input.illustrations_only.is_none() + && input.drawings_only.is_none(), "compare_revision requires an unfiltered review view" ); let draft = server.0.drafts.snapshot(&input.draft_id, input.revision)?; @@ -59,7 +69,7 @@ pub(super) async fn run( } server .render(ctx, move |state, engine, cancel| { - render(state, engine, &input, cancel) + render(state, engine, &input, finish, cancel) }) .await } @@ -68,6 +78,7 @@ fn render( state: &State, engine: &mut Engine, input: &Preview, + finish: Option, cancel: &Cancellation, ) -> Result { let draft = state.drafts.snapshot(&input.draft_id, input.revision)?; @@ -77,13 +88,22 @@ fn render( ); ensure!( input.region.is_none() - || matches!(input.view, Some(PreviewView::Layout | PreviewView::Review)), - "region requires view=layout or review" + || matches!(input.view, Some(PreviewView::Layout | PreviewView::Review)) + || finish.is_some(), + "region requires view=layout, view=review, or view=image with export_blur_px=0 (clear) or the PNG finish being compared" ); ensure!( input.compare_revision.is_none() || input.view == Some(PreviewView::Review), "compare_revision requires view=review" ); + ensure!( + input.drawings_only.is_none() || input.view == Some(PreviewView::Layout), + "drawings_only requires view=layout" + ); + ensure!( + input.drawings_only != Some(true) || input.illustrations_only != Some(true), + "Choose drawings_only or illustrations_only" + ); if input.view == Some(PreviewView::Paper) { ensure!( input.offset.is_none() @@ -112,15 +132,7 @@ fn render( "Review a single page without pagination" ); if let Some(region) = &input.region { - return review::local::page( - &state.drafts, - engine, - &draft, - section, - input, - region, - cancel, - ); + return review::local::page(state, engine, &draft, section, input, region, cancel); } ensure!( !state.preserve_reviews, @@ -128,7 +140,15 @@ fn render( ); let baselines = engine.review_baselines(&draft, section.clone(), page, cancel)?; let (preview, _) = engine.preview(&draft, section, page, cancel)?; - return review::page(&draft, number, page, &preview.png, &baselines, cancel); + return review::page( + &draft, + number, + page, + &preview.png, + &baselines, + &state.paper_focus, + cancel, + ); } if input.view == Some(PreviewView::Layout) { let result = engine.layout(&draft, section, input, cancel)?; @@ -138,7 +158,62 @@ fn render( input.offset.is_none() && input.limit.is_none(), "offset and limit require view=layout" ); - image(engine, &draft, section, page, input.fresh, cancel) + if let Some(finish) = finish { + let (preview, cached) = + engine.preview_with_refresh(&draft, section, page, input.fresh, cancel)?; + let original = review::decode_page(&preview.png)?; + let size = original.dimensions(); + let bounds = input + .region + .as_deref() + .map(|region| review::local::crop_bounds(region, size)) + .transpose()?; + let mut finished = if finish.active() { + finish.apply(&original, cancel)? + } else { + original + }; + if let Some([x, y, width, height]) = bounds { + finished = image::imageops::crop_imm(&finished, x, y, width, height).to_image(); + } + let mut metadata = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page_in_section":page,"cached":cached, + "photo_size":size,"crop_bounds":bounds,"image_size":finished.dimensions()}); + finish.write_metadata(&mut metadata); + let mut result = reply(format!("PNG 导出效果,原图像素。{metadata}"), metadata); + result.content.push(ContentBlock::image( + STANDARD.encode(export::png(&finished)?), + "image/png", + )); + return Ok(result); + } + let result = image( + engine, + &draft, + section, + page, + input.fresh, + !state.preserve_reviews, + cancel, + )?; + add_paper_focus(state, &draft, number, page, result) +} + +fn add_paper_focus( + state: &State, + draft: &Snapshot<'_>, + section: u32, + page: usize, + mut result: CallToolResult, +) -> Result { + if let Some(focus) = state.paper_focus.report(draft, section, page, false)? { + result + .content + .push(ContentBlock::text(format!("底纸边缘原尺寸检查 {focus}"))); + if let Some(data) = result.structured_content.as_mut() { + data["paper_focus_check"] = focus; + } + } + Ok(result) } fn paper(draft: &Snapshot<'_>) -> Result { @@ -163,19 +238,39 @@ fn image( section: Section, page: usize, fresh: bool, + review_allowed: bool, cancel: &Cancellation, ) -> Result { let number = section.number; - let contains_inline_image = section.text.contains("](data:image/"); + let contains_drawing = + section.text.contains("](data:image/") || section.text.contains("\\begin{circuitikz}"); + let read_only_sample = if draft.paper.is_some() && !review_allowed { + Some(engine.review_baselines(draft, section.clone(), page, cancel)?) + } else { + None + }; let (preview, cached) = engine.preview_with_refresh(draft, section, page, fresh, cancel)?; let mut message = format!("第 {number} 节 · 第 {page} 页 · 版本 {}", draft.revision); let mut data = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page_in_section":page,"cached":cached}); - if contains_inline_image { - let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。"; + if contains_drawing { + let hint = "如果当前页既有手绘图又有文字,在判断笔迹一致前,用 view=review 加 region 框住一段图线和旁边的字,同倍率比较粗细和墨色。先对照节点和分支标签与正文的字形、字号,再看箭杆和框线是否接近文字的主笔画。在横线纸上沿箭杆追到箭头。图线与纸线重合时,优先平移整图或调整节点间距,缩放整图会连同标签一起缩放。同页看图与字只传当前版,省略 compare_revision。看不清时说明还不能判断。"; message.push('\n'); message.push_str(hint); data["illustration_inspection"] = json!(hint); } + if draft.paper.is_some() && review_allowed { + let hint = "用 view=review 的 local_paper_ink_check 在原尺寸查看页首和正文,把新笔迹和附近原纸印迹放在一起看。页首纸线淡而字重时,先局部调 opacity,再查看过渡行。整页缩略图会掩盖反差。按 adjacent_row_check 检查邻行字形,有流程图或图标时按 diagram_perspective_check 对照四角、图线方向及近远宽窄。"; + message.push('\n'); + message.push_str(hint); + data["photo_review_arguments"] = json!({"draft_id":draft.id,"revision":draft.revision,"section":number,"page":page,"view":"review"}); + } + if let Some(sample) = read_only_sample + && let Some(check) = + review::local_ink_preview(draft, number, page, &preview.png, &sample, cancel)? + { + message.push_str(&format!("\n原纸与新增笔迹的局部反差 {check}")); + data["local_paper_ink_check"] = check; + } let mut result = reply(message, data); result .content diff --git a/crates/panache-mcp/src/review.rs b/crates/panache-mcp/src/review.rs index 9651257d..cc92b553 100644 --- a/crates/panache-mcp/src/review.rs +++ b/crates/panache-mcp/src/review.rs @@ -1,4 +1,9 @@ +mod consistency; +mod drawing; +pub(crate) use drawing::Drawing; pub mod local; +mod paper_ink; +pub(crate) use consistency::{Bounds, TextSample}; use crate::{controls, drafts::Snapshot, reply}; use anyhow::{Result, ensure}; @@ -82,7 +87,8 @@ fn ruling_offset(paper: &RgbaImage, point: [f32; 2], radius: i32) -> Option pub struct PageSample { pub baselines: Vec<[f32; 2]>, pub content_sha256: String, - pub illustration_and_text: Option<[[f32; 2]; 2]>, + pub text: Vec, + pub drawings: Vec, } // Suggest a crop around a sampled text line at native resolution, including neighboring paper. @@ -109,7 +115,7 @@ fn detail_region( ]) } -fn decode_page(png: &str) -> Result { +pub(crate) fn decode_page(png: &str) -> Result { let bytes = STANDARD.decode(png)?; let limits = Limits { max_file_bytes: bytes.len(), @@ -153,12 +159,51 @@ pub fn pixel_sha256(image: &RgbaImage) -> String { format!("{:x}", hash.finalize()) } +fn composite_on_paper( + finished: &mut RgbaImage, + paper: &RgbaImage, + cancel: &Cancellation, +) -> Result<()> { + for (row, base) in finished.rows_mut().zip(paper.rows()) { + cancel.check()?; + for (pixel, &under) in row.zip(base) { + let mut visible = under; + visible.blend(pixel); + *pixel = visible; + } + } + Ok(()) +} + +// Used by read-only image previews as well. All measurements use the visible output on the saved paper. +pub fn local_ink_preview( + draft: &Snapshot<'_>, + section: u32, + page: usize, + png: &str, + sample: &PageSample, + cancel: &Cancellation, +) -> Result> { + if draft.paper.is_none() { + return Ok(None); + } + let params = controls::parameters(draft, section, &draft.controls)?; + let mut finished = decode_page(png)?; + let paper = reference_paper(draft, finished.dimensions(), ¶ms)?; + if params.transparent_background { + composite_on_paper(&mut finished, &paper, cancel)?; + } + Ok(paper_ink::measure(sample, &paper, &finished, None, cancel)? + .map(|e| paper_ink::report(&e, draft.id, draft.revision, section, page))) +} + pub fn page( draft: &Snapshot<'_>, section: u32, page: usize, png: &str, sample: &PageSample, + focus: &crate::paper::focus::Cache, cancel: &Cancellation, ) -> Result { let params = controls::parameters(draft, section, &draft.controls)?; @@ -279,7 +324,7 @@ pub fn page( json!({"sampled":total,"supported_samples":v.len(),"median_abs_dy_px":v.get(v.len()/2)}) }) .collect::>(); - let evidence = json!({ + let mut evidence = json!({ "visibility":status, "photo_size":[w,h], "global_ink":{"rgba":params.fill,"opacity":params.ink_opacity,"thickness":params.ink_thickness,"softness":params.ink_softness,"depth_sigma":params.ink_depth_sigma}, @@ -292,10 +337,32 @@ pub fn page( "changed_pixels_outside_reference":outside, "transparent_png":params.transparent_background, }); + let checks = consistency::checks( + sample, + &paper, + &finished, + ¶ms, + draft.paper.is_some(), + cancel, + )?; + if let Some(rows) = &checks.rows { + evidence["adjacent_rows"] = rows.metrics.clone(); + } + if let Some(ink) = &checks.ink { + evidence["illustration_contrast"] = ink.metrics.clone(); + } + let local_ink = if draft.paper.is_some() { + paper_ink::measure(sample, &paper, &finished, None, cancel)? + } else { + None + }; + if let Some(value) = &local_ink { + evidence["local_paper_ink"] = value.clone(); + } let observation = draft.record_review( section, page, - "paper-review/1", + "paper-review/4", &pixel_digest, &sample.content_sha256, &evidence, @@ -312,33 +379,18 @@ pub fn page( metadata["photo_size"] = json!([w, h]); metadata["thumbnail_size"] = json!([result.width(), result.height()]); metadata["next_step"] = json!(next); - if let Some([[x0, y0], [x1, y1]]) = sample.illustration_and_text { - let padding = params.font_size.ceil(); - let x = |v: f32| v.clamp(0., w as f32) as u32; - let y = |v: f32| v.clamp(0., h as f32) as u32; - let (l, t, r, b) = ( - x(x0 - padding), - y(y0 - padding), - x(x1 + padding), - y(y1 + padding), - ); - let mut check = json!({"inspect":"Compare an actual diagram stroke or arrow and adjacent handwriting at the same zoom. Use the supplied preview_arguments as given for one revision; omit compare_revision. Check thickness and darkness. If the diagram alone looks heavy, revise the illustration source and preview again; preserve the surrounding writing. Describe what you can see. If the crop is unavailable or inconclusive, ask for visual confirmation."}); - if l < r - && t < b - && r - l <= REVIEW_MAX_EDGE - && b - t <= REVIEW_MAX_EDGE - && x0 >= 0. - && y0 >= 0. - && x1 <= w as f32 - && y1 <= h as f32 - { - check["preview_arguments"] = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"view":"review","region":[[l,t],[r,t],[r,b],[l,b]]}); - } else { - check["region_guidance"] = json!( - "Choose a small visible portion of the drawing and nearby writing from the finished page; use view=review with region for each at native scale." - ); - } - metadata["illustration_ink_check"] = check; + if let Some(e) = local_ink { + metadata["local_paper_ink_check"] = + paper_ink::report(&e, draft.id, draft.revision, section, page); + } + let arguments = |region| json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page,"view":"review","region":region}); + if let Some(rows) = checks.rows { + metadata["adjacent_row_check"] = rows.guidance(&arguments, + "Inspect these neighboring text rows at native size. The horizontal-to-vertical stretch describes letter proportions on the photo; paper vertical scale describes the change in letter height before photo projection. Compare both rows’ median values and inspect the crop. Check whether the difference suits the writing before making a local edit."); + } + if let Some(ink) = checks.ink { + metadata["illustration_ink_check"] = ink.guidance(&arguments, + "At native size compare a diagram label and nearby writing, then compare a straight frame or arrow shaft with a letter stem. Inspect letterforms, size, width, edge softness and darkness. The regions measure added ink against the saved paper. Different coverage, overlapping marks, color and paper lighting can affect the readings. Inspect thickness and darkness in the crops. If a crop misses a frame, arrow or identifiable nearby letters, move or expand the region to include comparable marks at native scale. On ruled paper trace each arrow to its head and check that it remains distinct from the ruling. If only the diagram needs changing, adjust its source or pen settings. Use each preview call as given for one revision; omit compare_revision."); } if draft.paper.is_some() { let mut appearance = json!({ @@ -355,6 +407,15 @@ pub fn page( } metadata["photo_appearance"] = appearance; } + drawing::add_check(&mut metadata, draft, section, page, sample, (w, h), None); + focus.add_review_guidance( + draft, + section, + page, + params.transparent_background, + true, + &mut metadata, + )?; metadata }; let mut response = reply( diff --git a/crates/panache-mcp/src/review/consistency.rs b/crates/panache-mcp/src/review/consistency.rs new file mode 100644 index 00000000..a41d9c28 --- /dev/null +++ b/crates/panache-mcp/src/review/consistency.rs @@ -0,0 +1,611 @@ +//! Same-page review in native output pixels. +use super::{PageSample, REVIEW_MAX_EDGE}; +use anyhow::Result; +use handwriting_core::{Cancellation, Parameters}; +use image::{Pixel, Rgba, RgbaImage}; +use serde_json::{Value, json}; + +type Region = [[u32; 2]; 4]; + +#[derive(Clone, Copy)] +pub(crate) struct Bounds { + left: f32, + top: f32, + right: f32, + bottom: f32, +} + +impl Bounds { + pub fn from_corners(corners: [[f32; 2]; 4]) -> Self { + let [x, y] = corners[0]; + let mut b = Self { + left: x, + top: y, + right: x, + bottom: y, + }; + for [x, y] in corners { + b.left = b.left.min(x); + b.top = b.top.min(y); + b.right = b.right.max(x); + b.bottom = b.bottom.max(y); + } + b + } + + fn union(self, b: Self) -> Self { + Self { + left: self.left.min(b.left), + top: self.top.min(b.top), + right: self.right.max(b.right), + bottom: self.bottom.max(b.bottom), + } + } + + pub(super) fn center(self) -> [f32; 2] { + [(self.left + self.right) / 2., (self.top + self.bottom) / 2.] + } + + fn gap(self, other: Self) -> f32 { + let x = (self.left.max(other.left) - self.right.min(other.right)).max(0.); + let y = (self.top.max(other.top) - self.bottom.min(other.bottom)).max(0.); + x.hypot(y) + } + + pub(super) fn intersects(self, other: Self) -> bool { + self.left < other.right + && self.right > other.left + && self.top < other.bottom + && self.bottom > other.top + } + + fn width(self) -> f32 { + self.right - self.left + } + + pub(super) fn height(self) -> f32 { + self.bottom - self.top + } + + pub(super) fn on_page(self, (w, h): (u32, u32)) -> bool { + self.width() > 0. + && self.height() > 0. + && self.left >= 0. + && self.top >= 0. + && self.right <= w as f32 + && self.bottom <= h as f32 + } + + pub(super) fn region(self, padding: f32, (w, h): (u32, u32)) -> Option { + let l = (self.left - padding).floor().clamp(0., w as f32) as u32; + let t = (self.top - padding).floor().clamp(0., h as f32) as u32; + let r = (self.right + padding).ceil().clamp(0., w as f32) as u32; + let b = (self.bottom + padding).ceil().clamp(0., h as f32) as u32; + (l < r && t < b).then_some([[l, t], [r, t], [r, b], [l, b]]) + } +} + +pub(crate) struct TextSample { + pub bounds: Bounds, + pub baseline: f32, + // Ratio of the two projected tile edge lengths normalized to the original tile aspect. + pub stretch: f32, + // Edited vertical centerline length in paper space, relative to the original tile height. + pub paper_vertical_scale: f32, +} + +pub(super) struct Check { + pub metrics: Value, + regions: Vec, +} + +impl Check { + pub fn guidance(&self, arguments: &impl Fn(Region) -> Value, inspect: &str) -> Value { + let mut check = json!({"inspect":inspect}); + if let [region] = self.regions.as_slice() { + check["preview_arguments"] = arguments(*region); + } else { + check["separate_preview_arguments"] = json!( + self.regions + .iter() + .copied() + .map(arguments) + .collect::>() + ); + } + check + } +} + +fn crops(pair: [Bounds; 2], anchors: [[f32; 2]; 2], size: (u32, u32), padding: f32) -> Vec { + if let Some(r) = pair[0].union(pair[1]).region(padding, size) + && r[2][0] - r[0][0] <= REVIEW_MAX_EDGE + && r[2][1] - r[0][1] <= REVIEW_MAX_EDGE + { + return vec![r]; + } + // At a distance, keep both samples at native resolution, centered on visible ink when available. + anchors + .iter() + .filter_map(|&p| Bounds::from_corners([p; 4]).region(padding.clamp(64., 240.), size)) + .collect() +} + +fn median(numbers: &mut [f32]) -> f32 { + numbers.sort_unstable_by(f32::total_cmp); + (numbers[numbers.len() / 2] + numbers[(numbers.len() - 1) / 2]) / 2. +} + +fn adjacent_rows(text: &[&TextSample], size: (u32, u32), params: &Parameters) -> Option { + let mut sorted = text.to_vec(); + sorted.sort_unstable_by(|a, b| a.baseline.total_cmp(&b.baseline)); + let spacing = params.line_spacing.max(1.); + let mut rows: Vec> = Vec::new(); + for glyph in sorted { + if let Some(row) = rows.last_mut() + && glyph.baseline - row[0].baseline <= spacing * 0.35 + { + row.push(glyph); + } else { + rows.push(vec![glyph]); + } + } + // Fields on the same baseline can belong to separate columns. Compare contiguous runs only. + let rows: Vec<_> = rows + .into_iter() + .map(|mut row| { + row.sort_unstable_by(|a, b| a.bounds.left.total_cmp(&b.bounds.left)); + let mut spans: Vec> = Vec::new(); + let mut right = f32::NEG_INFINITY; + for g in row { + if g.bounds.left - right > 2.5 * g.bounds.height().max(g.bounds.width()) { + spans.push(Vec::new()); + right = g.bounds.right; + } + right = right.max(g.bounds.right); + spans.last_mut().unwrap().push(g); + } + spans + }) + .collect(); + let mut best = None; + for pair in rows.windows(2) { + for upper in &pair[0] { + for lower in &pair[1] { + if lower[0].baseline - upper[0].baseline <= spacing * 2.5 + && let Some((factor, check)) = + compare_spans(upper, lower, size, params.font_size) + && best.as_ref().is_none_or(|(prior, _)| factor > *prior) + { + best = Some((factor, check)); + } + } + } + } + best.map(|(_, check)| check) +} + +fn compare_spans( + upper: &[&TextSample], + lower: &[&TextSample], + size: (u32, u32), + font_size: f32, +) -> Option<(f32, Check)> { + let extents = |row: &[&TextSample]| row.iter().map(|s| s.bounds).reduce(Bounds::union).unwrap(); + let a = extents(upper); + let b = extents(lower); + let left = a.left.max(b.left); + let right = a.right.min(b.right); + if left >= right { + return None; + } + let mid = (left + right) / 2.; + let radius = (font_size * 7.).clamp(80., 320.); + let measure = |row: &[&TextSample]| { + let samples = row.iter().filter(|g| { + let x = g.bounds.center()[0]; + x >= left.max(mid - radius) && x <= right.min(mid + radius) + }); + let mut stretches: Vec<_> = samples.clone().map(|g| g.stretch).collect(); + if stretches.len() < 3 { + return None; + } + let mut scales: Vec<_> = samples.clone().map(|g| g.paper_vertical_scale).collect(); + let bounds = samples.map(|g| g.bounds).reduce(Bounds::union)?; + Some(( + bounds, + median(&mut stretches), + median(&mut scales), + stretches.len(), + )) + }; + let (first, a, upper_scale, n) = measure(upper)?; + let (second, b, lower_scale, m) = measure(lower)?; + if first.center()[1] >= second.center()[1] { + return None; + } + let aspect_ratio = (a / b).max(b / a); + let scale_ratio = (upper_scale / lower_scale).max(lower_scale / upper_scale); + Some(( + aspect_ratio.max(scale_ratio), + Check { + metrics: json!({"sampled_glyphs":[n,m],"median_horizontal_to_vertical_stretch":[a,b], + "larger_to_smaller_ratio":aspect_ratio,"median_paper_vertical_scale":[upper_scale,lower_scale], + "larger_to_smaller_scale_ratio":scale_ratio,"photo_regions":[first.region(0.,size),second.region(0.,size)], + "selection":"Largest change in median aspect or median vertical scale between adjacent text rows in a shared horizontal span, at least three glyphs per row. Stretch includes photo projection. Vertical scale measures the edited height in paper space relative to each tile’s own original height."}), + regions: crops( + [first, second], + [first.center(), second.center()], + size, + font_size * 0.6, + ), + }, + )) +} + +fn light(pixel: Rgba) -> u8 { + let y = u16::from(pixel.to_luma()[0]); + (255 - ((255 - y) * u16::from(pixel[3])).div_ceil(255)) as u8 +} + +fn darkness( + region: Region, + paper: &RgbaImage, + finished: &RgbaImage, + toward: [f32; 2], + exclusions: &[Bounds], + cancel: &Cancellation, +) -> Result<(Value, [f32; 2])> { + let [l, t] = region[0]; + let [r, b] = region[2]; + let mut hist = [0u32; 256]; + let mut nearest = [(r + l) as f32 / 2., (b + t) as f32 / 2.]; + let mut min_distance = f32::INFINITY; + // Only boxes crossing this scan line can obscure ownership. Merge by marking the row spans. + let mut excluded = vec![false; (r - l) as usize]; + // Count runs through the added ink in four directions for a Crofton perimeter estimate. + // A one-pixel empty border also closes runs touching an edge of the sample. + let mut previous = vec![false; excluded.len() + 2]; + let mut current = previous.clone(); + let mut axial_runs = 0u64; + let mut diagonal_runs = 0u64; + let mut width_pixels = 0u64; + let mut excluded_pixels = 0u32; + for y in t..b { + excluded.fill(false); + for other in exclusions + .iter() + .filter(|g| (y as f32 + 0.5) >= g.top && (y as f32 + 0.5) < g.bottom) + { + let start = ((other.left - 0.5).ceil() as u32).clamp(l, r) - l; + let end = ((other.right - 0.5).ceil() as u32).clamp(l, r) - l; + excluded[start as usize..end as usize].fill(true); + } + cancel.check()?; + for x in l..r { + let i = (x - l) as usize + 1; + current[i] = false; + if excluded[(x - l) as usize] { + excluded_pixels += 1; + continue; + } + let delta = light(paper[(x, y)]).saturating_sub(light(finished[(x, y)])); + if delta >= 32 { + current[i] = true; + width_pixels += 1; + axial_runs += u64::from(!current[i - 1]) + u64::from(!previous[i]); + diagonal_runs += u64::from(!previous[i - 1]) + u64::from(!previous[i + 1]); + } + if delta >= 8 { + hist[usize::from(delta)] += 1; + let dx = x as f32 - toward[0]; + let dy = y as f32 - toward[1]; + let distance = dx * dx + dy * dy; + if distance < min_distance { + min_distance = distance; + nearest = [x as f32, y as f32]; + } + } + } + std::mem::swap(&mut current, &mut previous); + } + let perimeter = std::f64::consts::FRAC_PI_4 + * (axial_runs as f64 + diagonal_runs as f64 * std::f64::consts::FRAC_1_SQRT_2); + let width = (width_pixels >= 24).then(|| 2.0 * width_pixels as f64 / perimeter); + let count = hist.iter().sum::(); + let percentile = |percent: u64| { + let rank = (u64::from(count) * percent).div_ceil(100) as u32; + let mut total = 0; + hist.iter().position(|&n| { + total += n; + rank > 0 && total >= rank + }) + }; + Ok(( + json!({"region":region, "darkened_pixels":count, "overlap_pixels_excluded":excluded_pixels, "median_luma_drop":percentile(50),"p90_luma_drop":percentile(90), + "ink_footprint_width_px":width,"width_sample_pixels":width_pixels}), + nearest, + )) +} + +pub(super) struct Checks { + pub rows: Option, + pub ink: Option, +} + +pub(super) fn checks( + sample: &PageSample, + paper: &RgbaImage, + finished: &RgbaImage, + params: &Parameters, + photo: bool, + cancel: &Cancellation, +) -> Result { + let size = paper.dimensions(); + let text: Vec<_> = sample + .text + .iter() + .filter(|g| { + g.bounds.on_page(size) + && g.stretch.is_finite() + && g.stretch > 0. + && g.paper_vertical_scale.is_finite() + && g.paper_vertical_scale > 0. + }) + .collect(); + let rows = if photo { + adjacent_rows(&text, size, params) + } else { + None + }; + let mut ink = None; + if let Some(drawing) = sample.drawings.first().map(|d| d.bounds()) + && let Some(diagram_region) = drawing.region(0., size) + && let Some(nearest) = text.iter().min_by(|a, b| { + // A short line beside the diagram is usually a closer body-writing reference than a title above it. + // Use simple geometric priorities and retain the actual separation in the receipt. + let rank = |g: &TextSample| { + let b = g.bounds; + let side = (drawing.top..=drawing.bottom).contains(&b.center()[1]) + && drawing.gap(b) <= b.height().max(16.) * 4.; + (drawing.intersects(b), !side) + }; + rank(a) + .cmp(&rank(b)) + .then_with(|| drawing.gap(a.bounds).total_cmp(&drawing.gap(b.bounds))) + }) + { + let mut neighbors: Vec<_> = text + .iter() + .filter(|g| { + let on_same_side = (g.bounds.center()[0] < drawing.center()[0]) + == (nearest.bounds.center()[0] < drawing.center()[0]); + on_same_side + && (g.baseline - nearest.baseline).abs() <= params.line_spacing * 0.25 + && g.bounds.gap(nearest.bounds) <= nearest.bounds.height().max(16.) * 3. + && !drawing.intersects(g.bounds) + }) + .collect(); + neighbors.sort_unstable_by(|a, b| { + a.bounds + .gap(nearest.bounds) + .total_cmp(&b.bounds.gap(nearest.bounds)) + }); + let writing_box = neighbors + .into_iter() + .take(4) + .fold(nearest.bounds, |b, g| b.union(g.bounds)); + let text_region = writing_box.region(0., size).unwrap(); + let overlaps: Vec<_> = text + .iter() + .map(|g| g.bounds) + .filter(|b| b.intersects(drawing)) + .collect(); + let (diagram, stroke) = darkness( + diagram_region, + paper, + finished, + nearest.bounds.center(), + &overlaps, + cancel, + )?; + let (writing, letter) = darkness(text_region, paper, finished, stroke, &[drawing], cancel)?; + let gap = drawing.gap(writing_box); + ink = Some(Check { + metrics: json!({"illustration":diagram,"nearby_text":writing,"minimum_luma_drop":8,"region_gap_px":gap, "distant_reference":gap > nearest.bounds.height().max(16.) * 6., + "width_method":"Width in native pixels estimated as twice the area divided by the four-direction Crofton perimeter of added ink with a luma drop of at least 32 (at least 24 pixels). Short strokes, joins, glyph shapes, softness and opacity affect this estimate. Compare the actual stems, lines and arrows in the crops.", + "sampling":"Saved-paper luma minus output luma (0–255) among darkened pixels in each layout box. Text boxes overlapping the diagram are masked from its sample, and diagram pixels are excluded from the writing sample. A distant reference or too little sampled ink needs visual confirmation."}), + regions: crops( + [drawing, writing_box], + [stroke, letter], + size, + params.font_size, + ), + }); + } + Ok(Checks { rows, ink }) +} + +#[cfg(test)] +mod tests { + use super::*; + use image::Rgba; + + fn bounds(left: f32, top: f32, right: f32, bottom: f32) -> Bounds { + Bounds::from_corners([[left, top], [right, top], [right, bottom], [left, bottom]]) + } + + #[test] + fn equally_dark_lines_have_distinct_footprint_widths() { + let paper = RgbaImage::from_pixel(112, 18, Rgba([255; 4])); + let mut finished = paper.clone(); + for (y, height) in [(1, 2), (9, 5)] { + for row in y..y + height { + for x in 5..105 { + finished[(x, row)] = Rgba([40, 40, 40, 255]); + } + } + } + let measure = |y, end| { + darkness( + [[0, y], [112, y], [112, end], [0, end]], + &paper, + &finished, + [0., 0.], + &[], + &Cancellation::default(), + ) + .unwrap() + .0 + }; + let thin = measure(0, 7); + let thick = measure(8, 18); + assert_eq!(thin["median_luma_drop"], thick["median_luma_drop"]); + assert!((1.8..2.3).contains(&thin["ink_footprint_width_px"].as_f64().unwrap())); + assert!((4.6..5.4).contains(&thick["ink_footprint_width_px"].as_f64().unwrap())); + } + + fn drawing(x: f32, y: f32, right: f32, bottom: f32) -> super::super::Drawing { + let corners = [[x, y], [right, y], [right, bottom], [x, bottom]]; + super::super::Drawing { + id: 1, + kind: "illustration", + layout_offset: 0, + details: None, + paper_corners: corners, + photo_corners: corners, + } + } + + #[test] + fn shared_pixels_do_not_count_as_diagram_or_body_ink() { + let paper = RgbaImage::from_pixel(80, 60, Rgba([255; 4])); + let mut finished = paper.clone(); + for y in 15..20 { + for x in 15..20 { + finished[(x, y)] = Rgba([0, 0, 0, 255]); + } + } + let sample = PageSample { + baselines: vec![], + content_sha256: String::new(), + drawings: vec![drawing(5., 5., 40., 40.)], + text: vec![TextSample { + bounds: bounds(15., 15., 20., 20.), + baseline: 22., + stretch: 1., + paper_vertical_scale: 1., + }], + }; + let check = checks( + &sample, + &paper, + &finished, + &Parameters::default(), + true, + &Cancellation::default(), + ) + .unwrap() + .ink + .unwrap(); + for name in ["illustration", "nearby_text"] { + let m = &check.metrics[name]; + assert_eq!(m["overlap_pixels_excluded"], 25); + assert_eq!(m["darkened_pixels"], 0); + assert!(m["p90_luma_drop"].is_null()); + assert!(m["ink_footprint_width_px"].is_null()); + } + } + + #[test] + fn distant_chart_and_writing_have_two_native_crops() { + let paper = RgbaImage::from_pixel(1300, 100, Rgba([255; 4])); + let mut finished = paper.clone(); + finished[(5, 5)] = Rgba([0, 0, 0, 255]); + finished[(1105, 5)] = Rgba([127, 127, 127, 255]); + let sample = PageSample { + baselines: vec![], + content_sha256: String::new(), + drawings: vec![drawing(0., 0., 100., 80.)], + text: vec![TextSample { + bounds: bounds(1100., 0., 1150., 40.), + baseline: 40., + stretch: 1., + paper_vertical_scale: 1., + }], + }; + let check = checks( + &sample, + &paper, + &finished, + &Parameters::default(), + true, + &Cancellation::default(), + ) + .unwrap() + .ink + .unwrap(); + assert_eq!(check.metrics["distant_reference"], true); + assert_eq!(check.metrics["illustration"]["p90_luma_drop"], 255); + assert_eq!(check.metrics["nearby_text"]["median_luma_drop"], 128); + assert_eq!(check.regions.len(), 2); + for (x, r) in [5, 1105].into_iter().zip(check.regions) { + assert!(r[0][0] <= x && x < r[2][0]); + assert!(r[2][0] - r[0][0] <= REVIEW_MAX_EDGE); + } + } + + #[test] + fn larger_size_jump_is_selected_even_with_equal_letter_proportions() { + let text: Vec<_> = [(28., 1.1, 1.), (58., 1., 1.), (88., 1., 1.5)] + .into_iter() + .flat_map(|(baseline, stretch, paper_vertical_scale)| { + (0..5).map(move |i| { + let x = 20. + i as f32 * 18.; + TextSample { + bounds: bounds(x, baseline - 16. * paper_vertical_scale, x + 14., baseline), + baseline, + stretch, + paper_vertical_scale, + } + }) + }) + .collect(); + let refs: Vec<_> = text.iter().collect(); + let check = adjacent_rows( + &refs, + (160, 120), + &Parameters { + line_spacing: 30., + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(check.metrics["larger_to_smaller_ratio"], 1.); + assert_eq!( + check.metrics["median_paper_vertical_scale"], + json!([1., 1.5]) + ); + assert_eq!(check.metrics["larger_to_smaller_scale_ratio"], 1.5); + } + + #[test] + fn separate_columns_do_not_form_a_comparable_row_pair() { + let text: Vec<_> = [(0., 20., 1.), (200., 20., 1.), (80., 60., 2.)] + .into_iter() + .flat_map(|(x, y, stretch)| { + (0..4).map(move |i| { + let l = x + i as f32 * 12.; + TextSample { + bounds: bounds(l, y - 15., l + 10., y), + baseline: y, + stretch, + paper_vertical_scale: 1., + } + }) + }) + .collect(); + let refs: Vec<_> = text.iter().collect(); + assert!(adjacent_rows(&refs, (400, 200), &Parameters::default()).is_none()); + } +} diff --git a/crates/panache-mcp/src/review/drawing.rs b/crates/panache-mcp/src/review/drawing.rs new file mode 100644 index 00000000..c1baeae8 --- /dev/null +++ b/crates/panache-mcp/src/review/drawing.rs @@ -0,0 +1,112 @@ +use super::{Bounds, PageSample, photo_point}; +use crate::drafts::Snapshot; +use serde_json::{Value, json}; + +type Quad = [[f32; 2]; 4]; + +pub(crate) struct Drawing { + pub id: u32, + pub kind: &'static str, + pub layout_offset: usize, + pub paper_corners: Quad, + pub details: Option<(usize, f32)>, + pub photo_corners: Quad, +} + +impl Drawing { + pub(super) fn bounds(&self) -> Bounds { + Bounds::from_corners(self.photo_corners) + } + + fn reference(&self, draft: &Snapshot<'_>) -> Quad { + let [a, b, c, d] = self.paper_corners; + let length = |a: [f32; 2], b: [f32; 2]| (b[0] - a[0]).hypot(b[1] - a[1]); + let half_w = (length(a, b) + length(d, c)) / 4.; + let half_h = (length(a, d) + length(b, c)) / 4.; + let center: [f32; 2] = std::array::from_fn(|i| (a[i] + b[i] + c[i] + d[i]) / 4.); + [ + [-half_w, -half_h], + [half_w, -half_h], + [half_w, half_h], + [-half_w, half_h], + ] + .map(|[x, y]| photo_point(draft, [center[0] + x, center[1] + y])) + } +} + +// 2026-11-27:比较同一位置、同一大小的纸面参考框;当前四角只代表图块外框。 +fn edge_differences(current: Quad, reference: Quad) -> [Option; 4] { + [(0, 1), (3, 2), (0, 3), (1, 2)].map(|(i, j)| { + let vector = |q: Quad| [q[j][0] - q[i][0], q[j][1] - q[i][1]]; + let ([x, y], [u, v]) = (vector(current), vector(reference)); + (x.hypot(y) >= 1. && u.hypot(v) >= 1.) + .then(|| (x * v - y * u).atan2(x * u + y * v).to_degrees().abs()) + }) +} + +fn bottom_to_top_width_ratio(q: Quad) -> Option { + let width = |a: [f32; 2], b: [f32; 2]| (b[0] - a[0]).hypot(b[1] - a[1]); + let top = width(q[0], q[1]); + (top >= 1.).then(|| width(q[3], q[2]) / top) +} + +pub(super) fn add_check( + metadata: &mut Value, + draft: &Snapshot<'_>, + section: u32, + page: usize, + sample: &PageSample, + size: (u32, u32), + crop: Option<[u32; 4]>, +) { + let Some(paper) = &draft.paper else { return }; + if paper.ruled && paper.projection.is_none() { + return; + } + let crop = crop.map(|[x, y, w, h]| { + Bounds::from_corners( + [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(|p| p.map(|v| v as f32)), + ) + }); + let mut items = Vec::new(); + let mut total = 0; + for drawing in &sample.drawings { + let bounds = drawing.bounds(); + if crop.is_some_and(|b| !bounds.intersects(b)) { + continue; + } + let Some(region) = bounds.region(paper.line_spacing, size) else { + continue; + }; + total += 1; + if items.len() >= 8 { + continue; + } + let reference = paper.projection.as_ref().map(|_| drawing.reference(draft)); + let preview = json!({"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, + "view":"review","region":region}); + items.push(json!({"id":drawing.id,"kind":drawing.kind,"current_photo_quad":drawing.photo_corners, + "paper_aligned_photo_quad":reference, + "axis_difference_deg_top_bottom_left_right":reference.map(|r|edge_differences(drawing.photo_corners,r)), + "bottom_to_top_width_ratio":bottom_to_top_width_ratio(drawing.photo_corners), + "paper_bottom_to_top_width_ratio":reference.and_then(bottom_to_top_width_ratio), + "separate_detail_alignment":drawing.details.map(|(n,gap)|json!({"visible_parts":n,"max_corner_offset_from_parent_px":gap})), + "preview_arguments":preview, + "native_image_arguments":{"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, + "view":"image","region":region,"export_blur_px":0}, + "layout_arguments":{"draft_id":draft.id,"revision":draft.revision,"section":section,"page":page, + "view":"layout","drawings_only":true,"offset":drawing.layout_offset,"limit":1}})); + } + if items.is_empty() { + return; + } + let hint = "检查 diagram_perspective_check:把图形作为和正文同一纸面上的整件,看原纸、图和附近字迹。沿原纸横线对照上、下横边或箭杆,再用跨行的纸边、栏线或横线端点核对左右侧边的倾斜及上下宽度变化。"; + let previous = metadata["next_step"].as_str().unwrap_or_default(); + metadata["next_step"] = json!(format!("{previous} {hint}").trim()); + metadata["diagram_perspective_check"] = json!({ + "alignment":paper.summary()["alignment"],"items":items,"visible_drawings_in_crop":total, + "guidance":hint, + "interpretation":"四角按左上、右上、右下、左下排列。参考框为以当前大小和位置沿纸面两轴放置后经现有模型投影的框。零角差只说明图框跟随模型;要在原纸上核对模型及图内线条、节点和标签。底边/顶边宽度比反映上下宽窄。rotated 只校准了整体旋转。拆分细节的偏移表示与按外框共同变换的预期位置之差;有意单独移字时可能合理。保留有意的斜线和已协调的图形。参考轴不足时报告不确定。", + "placement":"图文都偏时,先核对纸面标定,再决定是否用 paper_guides。仅此图不符且能在原纸上定位四角时,使用同版 layout_arguments 找整图 ID,再用 adjust_glyphs(whole_drawing=true, target_quad=实测四角) 同步框线、箭头和标签。只移位置用 whole_drawing=true 与 place_center。对比修前、修后裁区,核对相邻正文;移动后在新位置重查。超过八个图时可用 drawings_only 分页检查。" + }); +} diff --git a/crates/panache-mcp/src/review/local.rs b/crates/panache-mcp/src/review/local.rs index 13721f73..40b79950 100644 --- a/crates/panache-mcp/src/review/local.rs +++ b/crates/panache-mcp/src/review/local.rs @@ -3,23 +3,27 @@ mod regions; use super::{decode_page, reference_paper, rgb_delta, thumbnail}; use crate::{ - Preview, controls, - drafts::{Drafts, Section, Snapshot}, + Preview, State, controls, + drafts::{Section, Snapshot}, engine::Engine, reply, }; use anyhow::{Context, Result, ensure}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use handwriting_core::{Cancellation, Parameters, export}; -use image::{Pixel, RgbaImage}; +use image::RgbaImage; use regions::{Point, Regions}; use rmcp::model::{CallToolResult, ContentBlock}; use serde_json::json; +pub(crate) fn crop_bounds(region: &[[i32; 2]], size: (u32, u32)) -> Result<[u32; 4]> { + Ok(Regions::new(region, None, size)?.bounds) +} + struct Appearance { finished: RgbaImage, params: Parameters, - content_sha256: String, + sample: super::PageSample, fine_edit: bool, } @@ -37,7 +41,7 @@ impl Appearance { Ok(Self { finished: decode_page(&preview.png)?, params, - content_sha256: sample.content_sha256, + sample, fine_edit: preview.fine_edit, }) } @@ -48,7 +52,7 @@ impl Appearance { "Cannot compare local pixels: different_image_dimensions" ); ensure!( - self.content_sha256 == after.content_sha256, + self.sample.content_sha256 == after.sample.content_sha256, "Cannot compare local pixels: page_content_changed_or_repaginated" ); // Imported paper bytes are immutable per draft; generated stationery depends on controls. @@ -63,21 +67,14 @@ impl Appearance { fn composite(&mut self, paper: &RgbaImage, cancel: &Cancellation) -> Result<()> { if self.params.transparent_background { - for (pixels, bases) in self.finished.rows_mut().zip(paper.rows()) { - cancel.check()?; - for (pixel, &base) in pixels.zip(bases) { - let mut visible = base; - visible.blend(pixel); - *pixel = visible; - } - } + super::composite_on_paper(&mut self.finished, paper, cancel)?; } Ok(()) } } pub fn page( - drafts: &Drafts, + state: &State, engine: &mut Engine, draft: &Snapshot<'_>, section: Section, @@ -99,8 +96,9 @@ pub fn page( let paper = reference_paper(draft, size, &after.params)?; after.composite(&paper, cancel)?; let before = if let Some(revision) = input.compare_revision { - let old = drafts.snapshot(draft.id, Some(revision))?; - let section = drafts + let old = state.drafts.snapshot(draft.id, Some(revision))?; + let section = state + .drafts .sections(old.id, revision, Some(number))? .pop() .context("Section absent in compare_revision")?; @@ -127,6 +125,14 @@ pub fn page( "after":evidence.after,"before":evidence.before,"difference":evidence.difference, "guidance":"Ink counts pixels whose largest visible RGB channel difference from the paper is at least 8. Revision differences apply the same threshold to before and after appearances; outside_union_changed_pixels covers the entire page outside both polygons. This local inspection leaves full-page review status unchanged. Inspect the crops against the request, including whether disappearance was intended. Overlapping text and diagrams contribute to the same pixels. Check protected areas with another region. Stop once the target and protected areas meet the request; ask if intent or attribution is unclear." }); + if draft.paper.is_some() + && before.is_none() + && let Some(e) = + super::paper_ink::measure(&after.sample, &paper, &after.finished, Some(region), cancel)? + { + metadata["local_paper_ink_check"] = + super::paper_ink::report(&e, draft.id, draft.revision, number, page); + } if let Some(prior) = &before && prior.fine_edit != after.fine_edit { @@ -136,6 +142,25 @@ pub fn page( "guidance": "Fine edit applies ink variation to individual glyphs. Switching rendering modes can change unedited writing. All measured differences remain visible changes; inspect protected areas before judging the edit." }); } + super::drawing::add_check( + &mut metadata, + draft, + number, + page, + &after.sample, + size, + Some(regions.bounds), + ); + if before.is_none() { + state.paper_focus.add_review_guidance( + draft, + number, + page, + after.params.transparent_background, + false, + &mut metadata, + )?; + } let mut response = reply(metadata.to_string(), metadata); let mut append = |label: &str, img: RgbaImage| -> Result<()> { response.content.push(ContentBlock::text(label)); diff --git a/crates/panache-mcp/src/review/paper_ink.rs b/crates/panache-mcp/src/review/paper_ink.rs new file mode 100644 index 00000000..e7eb5e52 --- /dev/null +++ b/crates/panache-mcp/src/review/paper_ink.rs @@ -0,0 +1,404 @@ +//! Compare added writing with the contrast of actual photographed marks in the same neighborhood. +use super::{PageSample, TextSample, contains}; +use crate::paper::focus::{luma, stroke_edges}; +use anyhow::Result; +use handwriting_core::Cancellation; +use image::RgbaImage; +use serde_json::{Value, json}; + +type Region = [[u32; 2]; 4]; + +fn rectangle(l: u32, t: u32, r: u32, b: u32) -> Region { + [[l, t], [r, t], [r, b], [l, b]] +} + +fn quantile(sorted: &[T], percent: usize) -> Option { + sorted + .get((sorted.len() * percent).div_ceil(100).saturating_sub(1)) + .copied() +} + +#[derive(Default)] +struct PaperMarks { + contrasts: Vec<(u8, [u32; 2])>, + tracks: usize, + near_writing: bool, +} + +impl PaperMarks { + fn supported(&self) -> bool { + self.contrasts.len() >= 6 && self.tracks >= 3 + } +} + +fn sample_marks( + paper: &RgbaImage, + region: Region, + boxes: &[Region], + near_limit: f32, + cancel: &Cancellation, +) -> Result { + let mut all = PaperMarks::default(); + let mut near = PaperMarks { + near_writing: true, + ..Default::default() + }; + for horizontal in [true, false] { + let axes = |[x, y]: [u32; 2]| if horizontal { [x, y] } else { [y, x] }; + let [l, t] = axes(region[0]); + let [r, b] = axes(region[2]); + if b - t < 8 || r - l < 12 { + continue; + } + let tracks = 16.min(b - t - 4); + for i in 0..tracks { + cancel.check()?; + let cross = t + 2 + (2 * i + 1) * (b - t - 4) / (2 * tracks); + let profile: Vec<_> = (l..r) + .map(|along| { + [cross - 2, cross, cross + 2].map(|transverse| { + let [x, y] = axes([along, transverse]); + luma(paper[(x, y)]) + }) + }) + .collect(); + let strokes = stroke_edges(&profile, 14, 3); + all.tracks += usize::from(!strokes.is_empty()); + let before = near.contrasts.len(); + for s in strokes { + let point = axes([l + s.darkest_at as u32, cross]); + all.contrasts.push((s.contrast, point)); + if boxes.iter().any(|b| { + let dx = point[0].abs_diff(point[0].clamp(b[0][0], b[2][0])); + let dy = point[1].abs_diff(point[1].clamp(b[0][1], b[2][1])); + (dx as f32).hypot(dy as f32) <= near_limit + }) { + near.contrasts.push((s.contrast, point)); + } + } + near.tracks += usize::from(near.contrasts.len() > before); + } + } + let mut marks = if near.supported() { near } else { all }; + marks.contrasts.sort_unstable_by_key(|p| p.0); + Ok(marks) +} + +fn glyph_core( + glyph: Region, + window: Region, + paper: &RgbaImage, + finished: &RgbaImage, +) -> (usize, Option) { + let mut histogram = [0usize; 256]; + let mut count = 0usize; + for y in glyph[0][1].max(window[0][1])..glyph[2][1].min(window[2][1]) { + for x in glyph[0][0].max(window[0][0])..glyph[2][0].min(window[2][0]) { + let drop = luma(paper[(x, y)]) - luma(finished[(x, y)]); + if drop >= 8 { + histogram[drop as usize] += 1; + count += 1; + } + } + } + let mut total = 0; + let rank = (count * 9).div_ceil(10); + let core = histogram + .iter() + .position(|n| { + total += n; + count >= 4 && total >= rank + }) + .map(|i| i as u8); + (count, core) +} + +fn inspect( + candidates: &[&TextSample], + anchor: &TextSample, + paper: &RgbaImage, + finished: &RgbaImage, + role: &str, + cancel: &Cancellation, +) -> Result { + let size = paper.dimensions(); + let [cx, cy] = anchor.bounds.center(); + let height = anchor.bounds.height().clamp(12., 100.); + let mut neighbors: Vec<_> = candidates + .iter() + .copied() + .filter(|g| { + let [x, y] = g.bounds.center(); + (g.baseline - anchor.baseline).abs() < height * 0.5 + && (y - cy).abs() <= height + && (x - cx).abs() <= (5. * height).clamp(90., 155.) + }) + .collect(); + neighbors.sort_unstable_by(|a, b| { + (a.bounds.center()[0] - cx) + .abs() + .total_cmp(&(b.bounds.center()[0] - cx).abs()) + }); + let boxes: Vec<_> = neighbors + .iter() + .take(12) + .filter_map(|g| g.bounds.region(0., size)) + .collect(); + let mut ink_box = boxes[0]; + for b in &boxes { + ink_box = rectangle( + ink_box[0][0].min(b[0][0]), + ink_box[0][1].min(b[0][1]), + ink_box[2][0].max(b[2][0]), + ink_box[2][1].max(b[2][1]), + ); + } + let (w, h) = size; + // Fixed limits keep all reported regions at native scale, including unusually large transformed glyphs. + let width = (ink_box[2][0] - ink_box[0][0] + 48).clamp(150, 480).min(w); + let window_height = (ink_box[2][1] - ink_box[0][1] + (height * 2.4).clamp(64., 132.) as u32) + .clamp(96, 232) + .min(h); + let l = ((ink_box[0][0] + ink_box[2][0]) / 2) + .saturating_sub(width / 2) + .min(w - width); + let t = ((ink_box[0][1] + ink_box[2][1]) / 2) + .saturating_sub(window_height / 2) + .min(h - window_height); + let region = rectangle(l, t, l + width, t + window_height); + let paper_marks = sample_marks(paper, region, &boxes, height, cancel)?; + let mut cores = Vec::new(); + let mut pixels = 0; + for bounds in &boxes { + cancel.check()?; + let (count, core) = glyph_core(*bounds, region, paper, finished); + pixels += count; + cores.extend(core); + } + cores.sort_unstable(); + let writing = quantile(&cores, 50); + let quartile = |q| quantile(&paper_marks.contrasts, q).map(|(v, _)| v); + let supported = paper_marks.supported(); + let (p25, p50, p75) = (quartile(25), quartile(50), quartile(75)); + let upper_difference = writing + .zip(p75) + .filter(|_| supported && pixels >= 12) + .map(|(ink, paper)| i16::from(ink) - i16::from(paper)); + let above = writing + .zip(p75) + .zip(upper_difference) + .map(|((ink, paper), delta)| delta >= 24 && f32::from(ink) >= f32::from(paper) * 1.35); + let status = match (writing, p25, p75) { + _ if pixels < 12 || writing.is_none() => "insufficient_added_ink", + _ if !supported => "insufficient_paper_marks", + (Some(_), Some(lo), Some(hi)) if hi - lo > 32 && f32::from(hi) > f32::from(lo) * 1.65 => { + "mixed_paper_marks" + } + _ if above == Some(true) => "writing_darker_than_sampled_marks", + _ => "inspect_local_contrast", + }; + Ok( + json!({"role":role,"status":status,"region":region,"writing_region":ink_box, + "added_writing":{"sampled_glyphs":cores.len(),"changed_pixel_samples":pixels,"median_glyph_p90_luma_drop":writing}, + "paper_marks":{"sampled_profiles":paper_marks.contrasts.len(),"supported_tracks":paper_marks.tracks,"supported":supported, + "within_one_glyph_height":paper_marks.near_writing,"p25_luma_drop":p25,"median_luma_drop":p50,"p75_luma_drop":p75, + "median_sample_point":quantile(&paper_marks.contrasts,50).map(|(_,point)|point)}, + "writing_minus_paper_p75":upper_difference,"clearly_above_paper_p75":above, + "writing_minus_paper_median":writing.zip(p50).filter(|_|supported).map(|(a,b)|i16::from(a)-i16::from(b))}), + ) +} + +pub(super) fn measure( + sample: &PageSample, + paper: &RgbaImage, + finished: &RgbaImage, + polygon: Option<&[[i32; 2]]>, + cancel: &Cancellation, +) -> Result> { + let mut glyphs: Vec<_> = sample + .text + .iter() + .filter(|g| { + g.bounds.on_page(paper.dimensions()) + && g.baseline.is_finite() + && !sample + .drawings + .iter() + .any(|d| d.bounds().intersects(g.bounds)) + && polygon.is_none_or(|p| contains(p, g.bounds.center())) + }) + .collect(); + glyphs.sort_unstable_by(|a, b| a.bounds.center()[1].total_cmp(&b.bounds.center()[1])); + let Some(first) = glyphs.first() else { + return Ok(None); + }; + let mut rows = Vec::new(); + if let Some(poly) = polygon { + let extent = |axis: usize| { + poly.iter().fold((i32::MAX, i32::MIN), |(l, r), p| { + (l.min(p[axis]), r.max(p[axis])) + }) + }; + let mid = [0, 1].map(|axis| { + let (l, r) = extent(axis); + (l + r) as f32 / 2. + }); + let distance = |g: &TextSample| { + let [x, y] = g.bounds.center(); + (x - mid[0]).hypot(y - mid[1]) + }; + let anchor = glyphs + .iter() + .min_by(|a, b| distance(a).total_cmp(&distance(b))) + .unwrap(); + rows.push(inspect( + &glyphs, + anchor, + paper, + finished, + "selected_writing", + cancel, + )?); + } else { + let last = *glyphs.last().unwrap(); + let middle = glyphs[glyphs.len() / 2]; + let separation = |g: &TextSample| g.bounds.height().clamp(12., 100.) * 0.7; + let below = |g: &TextSample, other: &TextSample| { + g.bounds.center()[1] - other.bounds.center()[1] > separation(other) + }; + let next = glyphs + .iter() + .copied() + .find(|g| below(g, first) && g.baseline - first.baseline > separation(first)); + let mut anchors = vec![("first_written_row", *first)]; + if let Some(g) = next + && below(last, g) + { + anchors.push(("following_written_row", g)); + } + if below(middle, anchors.last().unwrap().1) && below(last, middle) { + anchors.push(("middle_writing", middle)); + } + if below(last, anchors.last().unwrap().1) { + anchors.push(("lower_writing", last)); + } + for (role, anchor) in anchors { + rows.push(inspect(&glyphs, anchor, paper, finished, role, cancel)?); + } + } + Ok(Some( + json!({"samples":rows,"method":"Original paper: smaller of the two local light-to-dark edge drops on paired dark strokes, supported on parallel profiles. Added writing: median of each sampled text box’s 90th percentile paper-minus-output visible luma drop (changed pixels >=8). Scale 0–255. Profiles can revisit a single printed rule. The paper sample favors marks within one local glyph height, then uses the native context crop if support is sparse. The numeric difference flag requires added writing to exceed the paper P75 by at least 24 luma levels and by a factor of 1.35. Mark type, lighting and intended pen color affect the comparison."}), + )) +} + +pub(super) fn report( + evidence: &Value, + draft: &str, + revision: u32, + section: u32, + page: usize, +) -> Value { + let mut data = evidence.clone(); + for sample in data["samples"].as_array_mut().unwrap() { + sample["preview_arguments"] = json!({"draft_id":draft,"revision":revision,"section":section,"page":page,"view":"review","region":sample["region"]}); + sample["layout_arguments"] = json!({"draft_id":draft,"revision":revision,"section":section,"page":page,"view":"layout","region":sample["writing_region"],"limit":32}); + } + data["guidance"] = json!( + "先看最上方实际落字,再对照中、下部或用户点名区域。按 preview_arguments 在原尺寸比较底纸/成图,核对当地横线、印字与新增字迹是否适合相互参照。差值是局部参考;淡横线与较深手写字可以是有意搭配。效果确实太重时,用 layout_arguments 核对目标字形,按当地印迹分区小调 opacity;有渐变时分段过渡,保留合适区域,用同一裁区复看。印迹混杂时仍可参考新增笔迹高于纸面样本较深四分位的幅度;先核对参照笔画种类和位置。印迹不足时仅凭数字不能判断。" + ); + data +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::review::Bounds; + use image::Rgba; + + fn check(source: impl Fn(u32, u32) -> u8, ink: u8) -> Value { + let paper = RgbaImage::from_fn(320, 180, |x, y| { + let v = source(x, y); + Rgba([v, v, v, 255]) + }); + let mut output = paper.clone(); + let mut text = vec![]; + for x in [114, 138, 162, 186] { + text.push(TextSample { + bounds: Bounds::from_corners([ + [x as f32, 66.], + [(x + 14) as f32, 66.], + [(x + 14) as f32, 88.], + [x as f32, 88.], + ]), + baseline: 88., + stretch: 1., + paper_vertical_scale: 1., + }); + for yy in 69..85 { + for xx in x + 3..x + 6 { + let v = paper[(xx, yy)][0].saturating_sub(ink); + output[(xx, yy)] = Rgba([v, v, v, 255]); + } + } + } + let sample = PageSample { + baselines: vec![], + text, + drawings: vec![], + content_sha256: String::new(), + }; + measure(&sample, &paper, &output, None, &Cancellation::default()) + .unwrap() + .unwrap()["samples"][0] + .clone() + } + + #[test] + fn local_light_and_dark_rules_do_not_imply_the_same_ink_direction() { + let faint = check(|_, y| if y % 14 < 2 { 186 } else { 224 }, 120); + assert_eq!(faint["status"], "writing_darker_than_sampled_marks"); + assert_eq!(faint["paper_marks"]["median_luma_drop"], 38); + assert_eq!(faint["added_writing"]["median_glyph_p90_luma_drop"], 120); + let dark = check(|_, y| if y % 14 < 2 { 90 } else { 224 }, 120); + assert_eq!(dark["status"], "inspect_local_contrast"); + assert_eq!(dark["paper_marks"]["median_luma_drop"], 134); + } + + #[test] + fn mixed_print_shadow_and_invisible_writing_have_explicit_limits() { + let mixed = check( + |_, y| { + if y % 14 > 1 { + 224 + } else if y % 28 < 2 { + 191 + } else { + 88 + } + }, + 141, + ); + assert_eq!(mixed["status"], "mixed_paper_marks"); + assert_eq!(mixed["clearly_above_paper_p75"], false); + let heavier = check( + |_, y| { + if y % 14 > 1 { + 224 + } else if y % 28 < 2 { + 191 + } else { + 88 + } + }, + 205, + ); + assert_eq!(heavier["status"], "mixed_paper_marks"); + assert_eq!(heavier["clearly_above_paper_p75"], true); + let shadow = check(|x, _| 192 + (x / 16) as u8, 110); + assert_eq!(shadow["status"], "insufficient_paper_marks"); + assert!(shadow["writing_minus_paper_median"].is_null()); + let empty = check(|_, y| if y % 14 < 2 { 185 } else { 215 }, 0); + assert_eq!(empty["status"], "insufficient_added_ink"); + assert!(empty["added_writing"]["median_glyph_p90_luma_drop"].is_null()); + } +} diff --git a/crates/panache-mcp/src/save.rs b/crates/panache-mcp/src/save.rs index 565c81e2..bce5507e 100644 --- a/crates/panache-mcp/src/save.rs +++ b/crates/panache-mcp/src/save.rs @@ -101,13 +101,22 @@ fn prepare_and_save(state: &State, input: &Save, mut style: Option