diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a089f32..8672fff0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ - MCP 新建稿件默认启用内置 TeX 扩展包,也可从用户配置的本地文件选择自定义包。续写沿用建稿时的包定义,已有旧稿继续按原方式处理。 +- 精调画布拖动相距很远的字块时只重绘受影响的区域,密集选区合并绘制。普通页和精调页减少了生成墨迹时的重复采样和内存分配。 +- 新版精调草稿可在上一版继续调整位置、角度等参数。用旧版打开并重存后再升级,可恢复原布局和透明度渐变。旧版重新编辑过的字块采用其最新调整。 + +- 普通预览复制和保存透明 PNG 时保留彩色笔迹的边缘颜色,与导出 ZIP 中的 PNG 一致。 + +- 正文、公式与图表在缩放和旋转时保留墨迹边缘的灰度,改善细笔和斜线的锯齿。放大精调画布拖动笔画时,笔画边缘与松手、复制及导出时一致。调整一组字的不透明度时复用已有粗细和柔化效果。打开已有精调的稿件时保留原来的字块位置和旋转中心。 + - 字体排版新增可编辑的实时笔迹样张与字体选择画廊,可预览内置、导入及英文字体的真实字形,并用同一句话比较不同字体。 - 工作台编辑器和新手指南可查看已启用的 TeX 扩展包数量,打开扩展包管理器或 AI 编写指南;新手指南还可直达公式演练场。 diff --git a/README.md b/README.md index b1024cbf..ed9ceb47 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ For text alone, paste the passage and say whether you want a printable page, wri | Flowchart strokes | RC circuit connections | | --- | --- | -| [![Flowchart strokes](assets/examples/process-states-detail-31f9bf0ddada.webp)](assets/examples/process-states-detail-31f9bf0ddada.webp) | [![RC circuit connections](assets/examples/rc-ladder-09c7d9dac754.webp)](assets/examples/rc-ladder-09c7d9dac754.webp) | +| [![Flowchart strokes](assets/examples/process-states-detail-66221f736d96.webp)](assets/examples/process-states-detail-66221f736d96.webp) | [![RC circuit connections](assets/examples/rc-ladder-e6d4e4ec1974.webp)](assets/examples/rc-ladder-e6d4e4ec1974.webp) | [Handwritten poem](assets/examples/spring-at-qiantang-lake-6806782d66f9.webp) diff --git a/README.zh-CN.md b/README.zh-CN.md index 301a3c71..0d617935 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -42,7 +42,7 @@ Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 | 流程图线条近景 | RC 电路接线近景 | | --- | --- | -| [![流程图线条近景](assets/examples/process-states-detail-31f9bf0ddada.webp)](assets/examples/process-states-detail-31f9bf0ddada.webp) | [![RC 电路接线近景](assets/examples/rc-ladder-09c7d9dac754.webp)](assets/examples/rc-ladder-09c7d9dac754.webp) | +| [![流程图线条近景](assets/examples/process-states-detail-66221f736d96.webp)](assets/examples/process-states-detail-66221f736d96.webp) | [![RC 电路接线近景](assets/examples/rc-ladder-e6d4e4ec1974.webp)](assets/examples/rc-ladder-e6d4e4ec1974.webp) | [《钱塘湖春行》](assets/examples/spring-at-qiantang-lake-6806782d66f9.webp) diff --git a/app/lib/models/fine_edit.dart b/app/lib/models/fine_edit.dart index d501f90d..7038abaa 100644 --- a/app/lib/models/fine_edit.dart +++ b/app/lib/models/fine_edit.dart @@ -58,8 +58,9 @@ class FineGlyph { } class FinePage { - const FinePage(this.key, this.atlas, this.glyphs); + const FinePage(this.key, this.atlas, this.glyphs, {this.rollbackKey}); final String key; + final String? rollbackKey; final Uint8List atlas; final List glyphs; @@ -90,10 +91,13 @@ class FinePage { key, base64Decode(json['atlas'] as String), List.unmodifiable(glyphs), + rollbackKey: _readRollbackKey(json['rollback_key'], key), ); } } +typedef FineOpacityRamp = ({int start, int from, int end, int to}); + typedef FineAdjustment = ({ int id, int dx, @@ -101,6 +105,7 @@ typedef FineAdjustment = ({ int scale, int angle, int opacity, + FineOpacityRamp? opacityRamp, int? color, int thickness, int softness, @@ -114,6 +119,7 @@ FineAdjustment defaultFineAdjustment(int id) => ( scale: 100, angle: 0, opacity: 100, + opacityRamp: null, color: null, thickness: 0, softness: 0, @@ -122,12 +128,16 @@ FineAdjustment defaultFineAdjustment(int id) => ( bool _validKey(String key) => RegExp(r'^[0-9a-f]{64}$').hasMatch(key); +String? _readRollbackKey(Object? value, String key) => + value is String && value != key && _validKey(value) ? value : null; + class FineEdits { - FineEdits(this.key, Map glyphs) + FineEdits(this.key, Map glyphs, {this.rollbackKey}) : glyphs = Map.unmodifiable(glyphs); static const maxGlyphs = 10000; final String key; final Map glyphs; + final String? rollbackKey; factory FineEdits.fromJson(Map json) { final key = json['key'] as String; @@ -154,6 +164,11 @@ class FineEdits { 'scale': edit.scale, 'angle': edit.angle, 'opacity': edit.opacity, + if (edit.opacityRamp case final r?) + 'opacity_ramp': [ + [r.start, r.from], + [r.end, r.to], + ], if (edit.thickness != 0) 'thickness': edit.thickness, if (edit.softness != 0) 'softness': edit.softness, if (edit.warp case final warp?) 'warp': coefficients(warp), @@ -179,6 +194,7 @@ FineAdjustment _readAdjustment(Map value) { scale: value['scale'] as int, angle: value['angle'] as int, opacity: value['opacity'] as int, + opacityRamp: _readRamp(value['opacity_ramp']), thickness: value['thickness'] as int? ?? 0, softness: value['softness'] as int? ?? 0, warp: warp, @@ -199,6 +215,21 @@ FineAdjustment _readAdjustment(Map value) { return edit; } +FineOpacityRamp? _readRamp(Object? value) { + if (value == null) return null; + if (value case [[int start, int from], [int end, int to]] + when start >= 0 && + start < end && + end <= 100 && + from >= 0 && + from <= 100 && + to >= 0 && + to <= 100) { + return (start: start, from: from, end: end, to: to); + } + throw const FormatException('Invalid fine edit opacity ramp'); +} + int? _readColor(List? rgb) { if (rgb == null) return null; if (rgb.length != 3 || rgb.any((c) => c is! int || c < 0 || c > 255)) { diff --git a/app/lib/models/fine_edit_history.dart b/app/lib/models/fine_edit_history.dart index 963ac89f..d7056993 100644 --- a/app/lib/models/fine_edit_history.dart +++ b/app/lib/models/fine_edit_history.dart @@ -12,20 +12,17 @@ class FineEditHistory { Map adjustmentsFor(String key) => _current?.key == key ? _current!.glyphs : const {}; - bool restore(String text, Map json) { - try { - _current = FineEdits.fromJson(json); - _text = text; - return true; - } on FormatException { - _current = null; - } on TypeError { - _current = null; - } - return false; + void restore(String text, FineEdits edits) { + _current = edits; + _text = text; } - bool apply(String text, String key, List changes) { + bool apply( + String text, + String key, + List changes, { + String? rollbackKey, + }) { final saved = forText(text); final previous = saved?.key == key ? saved : null; final next = {...?previous?.glyphs}; @@ -44,7 +41,11 @@ class FineEditHistory { _undo.add(previous); _redo.clear(); _text = text; - _current = FineEdits(key, next); + _current = FineEdits( + key, + next, + rollbackKey: rollbackKey ?? previous?.rollbackKey, + ); return true; } @@ -58,7 +59,9 @@ class FineEditHistory { final from = redo ? _redo : _undo; final to = redo ? _undo : _redo; to.add(_current); - _current = from.removeLast() ?? FineEdits(_current!.key, const {}); + _current = + from.removeLast() ?? + FineEdits(_current!.key, const {}, rollbackKey: _current!.rollbackKey); return true; } } diff --git a/app/lib/services/fine_draft.dart b/app/lib/services/fine_draft.dart new file mode 100644 index 00000000..809cd504 --- /dev/null +++ b/app/lib/services/fine_draft.dart @@ -0,0 +1,111 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; + +import '../models/fine_edit.dart'; + +/// Older clients rewrite only the fields they understand in flutter.workspace. +/// Keep the layout identity and gradients they cannot round-trip in a second slot. +class FineDraft { + static const extensionSlot = 'flutter.workspace.fine'; + + static ({Map edits, String? extension}) encode( + FineEdits fine, { + FinePage? page, + }) { + final edits = fine.toJson(); + // A previously saved single-key draft can learn its alias from a new preview. + final rollbackKey = + fine.rollbackKey ?? + (page?.key == fine.key ? page?.rollbackKey : null) ?? + fine.key; + final ramps = {}; + final common = >[]; + for (final row in (edits['glyphs'] as List).cast>()) { + final fields = Map.of(row); + final ramp = fields.remove('opacity_ramp'); + if (ramp != null) { + ramps[row['id'].toString()] = { + 'common': _digest(fields), + 'value': ramp, + }; + } + common.add(fields); + } + String? extension; + if (rollbackKey != fine.key || ramps.isNotEmpty) { + final recovery = { + 'key': rollbackKey, + 'layoutKey': fine.key, + 'common': _digest(common), + 'ramps': ramps, + }; + extension = jsonEncode({...recovery, 'checksum': _digest(recovery)}); + } + return ( + edits: {...edits, 'key': rollbackKey, 'layoutKey': fine.key}, + extension: extension, + ); + } + + static FineEdits? read(Map json, String? extension) { + final FineEdits common; + try { + common = FineEdits.fromJson(json); + } on FormatException { + return null; + } on TypeError { + return null; + } + + try { + if (json.containsKey('layoutKey')) { + return _withLayout(json, json['layoutKey'], common.key); + } + if (extension == null || extension.isEmpty) return common; + final extra = jsonDecode(extension) as Map; + final checksum = extra.remove('checksum'); + if (extra['key'] != common.key || checksum != _digest(extra)) { + return common; + } + final rows = (common.toJson()['glyphs'] as List) + .cast>(); + // An edit made on the older renderer uses its own geometry. An unchanged + // legacy save can reopen with the exact original layout. + final layout = extra['common'] == _digest(rows) + ? extra['layoutKey'] + : common.key; + final ramps = extra['ramps'] as Map; + for (final row in rows) { + final saved = ramps[row['id'].toString()]; + // A deleted or independently replaced glyph can reuse the same ID. + if (!row.containsKey('opacity_ramp') && + saved is Map && + saved['common'] == _digest(row)) { + row['opacity_ramp'] = saved['value']; + } + } + return _withLayout({'glyphs': rows}, layout, common.key); + } on FormatException { + return common; + } on TypeError { + return common; + } + } + + static FineEdits _withLayout( + Map json, + Object? layout, + String rollbackKey, + ) { + final restored = FineEdits.fromJson({...json, 'key': layout}); + return FineEdits( + restored.key, + restored.glyphs, + rollbackKey: restored.key == rollbackKey ? null : rollbackKey, + ); + } + + static String _digest(Object value) => + sha256.convert(utf8.encode(jsonEncode(value))).toString(); +} diff --git a/app/lib/services/workspace.dart b/app/lib/services/workspace.dart index a06a82af..312c8da7 100644 --- a/app/lib/services/workspace.dart +++ b/app/lib/services/workspace.dart @@ -14,6 +14,7 @@ import '../utils/text_tools.dart'; import '../utils/image_data.dart'; import 'api.dart'; import 'engine_gateway.dart'; +import 'fine_draft.dart'; import '../view_models/generation_view_model.dart'; import '../tex_packages/tex_package.dart'; import '../tex_packages/tex_package_engine.dart'; @@ -73,7 +74,14 @@ class Workspace extends ChangeNotifier { void applyFineEdits(FinePage page, List values) { if (busy || previewStale || _finePageKey != page.key) return; - if (_fineHistory.apply(text, page.key, values)) edit(inkOnly: true); + if (_fineHistory.apply( + text, + page.key, + values, + rollbackKey: page.rollbackKey, + )) { + edit(inkOnly: true); + } } void stepFineHistory({required bool redo}) { @@ -111,6 +119,7 @@ class Workspace extends ChangeNotifier { bool connected = false, disposed = false, initialized = false; WorkspaceStorage? storage; Future _writes = Future.value(); + String? _confirmedFineExtension; int _connection = 0, _editRevision = 0; int get editRevision => _editRevision; String? get previewTaskId => generation.previewTaskId; @@ -287,7 +296,14 @@ class Workspace extends ChangeNotifier { }; } if (data['fineEdits'] case final Map edits) { - if (_fineHistory.restore(text, edits)) fineEnabled = true; + final restored = FineDraft.read( + edits, + storage?.read(FineDraft.extensionSlot), + ); + if (restored != null) { + _fineHistory.restore(text, restored); + fineEnabled = true; + } } if (data['texPackages'] case final Map snapshot) { final previous = _texPackages.toStorageJson(); @@ -379,14 +395,19 @@ class Workspace extends ChangeNotifier { saveTimer?.cancel(); final font = fontFile; final fineEdits = _fineHistory.forText(text); + final fineDraft = fineEdits != null && fineEdits.glyphs.isNotEmpty + ? FineDraft.encode( + fineEdits, + page: inkPages.elementAtOrNull(page)?.fine, + ) + : null; final snapshot = jsonEncode({ 'text': text, 'settings': settings.toJson(), 'texPackages': texPackageSnapshot.toJson(), 'images': images, 'uploadedFont': font != null || _fontRestorePending, - if (fineEdits != null && fineEdits.glyphs.isNotEmpty) - 'fineEdits': fineEdits.toJson(), + if (fineDraft != null) 'fineEdits': fineDraft.edits, }); final packageWrite = _texPackagesDirty ? _saveTexPackages() @@ -396,6 +417,7 @@ class Workspace extends ChangeNotifier { snapshot, font: font, saveFont: !_fontRestorePending, + fineExtension: fineDraft?.extension, ); return Future.wait([packageWrite, draftWrite]) .then((results) => results.every((ok) => ok)); @@ -415,6 +437,7 @@ class Workspace extends ChangeNotifier { String value, { Upload? font, bool saveFont = false, + String? fineExtension, }) { final storage = this.storage; if (storage == null) return Future.value(false); @@ -427,6 +450,18 @@ class Workspace extends ChangeNotifier { _savedFont = font; } await storage.write(key, value); + if (key == 'flutter.workspace') { + final extension = fineExtension ?? ''; + final cached = storage.read(FineDraft.extensionSlot); + // SharedPreferences updates its cache before the platform write. + // A cached value alone cannot confirm a failed write or clear. + if (!(cached == null && extension.isEmpty) && + (_confirmedFineExtension != extension || cached != extension)) { + _confirmedFineExtension = null; + await storage.write(FineDraft.extensionSlot, extension); + } + _confirmedFineExtension = extension; + } }) .then( (_) => true, diff --git a/app/lib/utils/fine_raster.dart b/app/lib/utils/fine_raster.dart index 7de40eac..27eccce0 100644 --- a/app/lib/utils/fine_raster.dart +++ b/app/lib/utils/fine_raster.dart @@ -1,9 +1,9 @@ -import 'dart:async'; import 'dart:math' as math; import 'dart:typed_data'; import 'dart:ui' as ui; import 'paper_exif.dart'; +import 'rgba_png.dart'; import '../models/fine_edit.dart'; import '../models/fine_transform.dart'; @@ -25,11 +25,22 @@ class FinePose { final corners = fineCorners(glyph.width, glyph.height, scale, cos, sin); if (fineWarpFits(warp, corners)) { final m = [...coefficients(warp), 1.0]; - final points = corners.map((point) => origin + mapFinePoint(m, point)); - center = origin + mapFinePoint(m, ui.Offset.zero); - bounds = points + ui.Rect projectedBounds(List points) => points + .map((point) => origin + mapFinePoint(m, point)) .map((point) => ui.Rect.fromPoints(point, point)) .reduce((a, b) => a.expandToInclude(b)); + final padded = fineCorners( + glyph.width + 1, + glyph.height + 1, + scale, + cos, + sin, + ); + center = origin + mapFinePoint(m, ui.Offset.zero); + bounds = projectedBounds(corners); + paintBounds = fineWarpFits(warp, padded) + ? projectedBounds(padded) + : bounds; projection = m; inverse = inverseFineWarp(warp); return; @@ -42,13 +53,17 @@ class FinePose { width: scale * (cos.abs() * glyph.width + sin.abs() * glyph.height), height: scale * (sin.abs() * glyph.width + cos.abs() * glyph.height), ); + paintBounds = aligned + ? bounds + : bounds.inflate(scale * (cos.abs() + sin.abs()) / 2); } final double scale, angle; final ui.Offset origin; late final ui.Offset center; late final List? projection, inverse; late final double cos, sin; - late final ui.Rect bounds; + late final ui.Rect bounds, paintBounds; + bool get aligned => inverse == null && scale == 1 && angle == 0; bool hit(FineGlyph glyph, ui.Offset point) { if (!bounds.contains(point)) return false; @@ -60,36 +75,178 @@ class FinePose { } } -Future _image(Uint8List bytes, int width, int height) { - final result = Completer(); - ui.decodeImageFromPixels( - bytes, - width, - height, - ui.PixelFormat.rgba8888, - result.complete, - ); - return result.future; -} +typedef FineFrame = ({ + ui.Image image, + Map edits, + InkLook look, +}); + +typedef _Shape = ({ + double thickness, + double softness, + int opacity, + FineOpacityRamp? ramp, +}); -typedef _Shape = ({double thickness, double softness}); +typedef _Mask = ({_Shape shape, Uint8List base, Uint8List pixels}); _Shape _shape(InkLook look, FineAdjustment? edit) => ( + opacity: edit?.opacity ?? 100, + ramp: edit?.opacityRamp, thickness: (look.thickness + (edit?.thickness ?? 0) / 10).clamp(-2.0, 2.0), softness: (look.softness + (edit?.softness ?? 0) / 10).clamp(0.0, 2.0), ); +int _sample(Uint8List mask, int width, int height, double x, double y) { + final ix = x.floor(), iy = y.floor(); + final fx = x - ix, fy = y - iy; + int tap(int x, int y) => + x >= 0 && y >= 0 && x < width && y < height ? mask[y * width + x] : 0; + final top = tap(ix, iy) * (1 - fx) + tap(ix + 1, iy) * fx; + final bottom = tap(ix, iy + 1) * (1 - fx) + tap(ix + 1, iy + 1) * fx; + return (top * (1 - fy) + bottom * fy).round(); +} + +ui.Rect _roundOut(ui.Rect rect) => ui.Rect.fromLTRB( + rect.left.floorToDouble(), + rect.top.floorToDouble(), + rect.right.ceilToDouble(), + rect.bottom.ceilToDouble(), +); + +// Tight patches inside a bounded grid keep distant ink independent. Dense +// selections share a picture per occupied cell (at most 16 x 16 per page). +class _FinePatchGrid { + _FinePatchGrid(ui.Rect page, ui.Rect clip) + : visible = _roundOut(clip.intersect(page)).intersect(page), + cellSize = math.max( + (page.longestSide / 16).ceil(), + math.min(256, (page.longestSide / 2).ceil()), + ); + + final ui.Rect visible; + final int cellSize; + final patches = <(int, int), _FinePatch>{}; + + Iterable<(int, int)> cells(ui.Rect rect) sync* { + final area = rect.intersect(visible); + if (area.isEmpty) return; + final right = (area.right / cellSize).ceil(); + final bottom = (area.bottom / cellSize).ceil(); + for (var y = area.top ~/ cellSize; y < bottom; y++) { + for (var x = area.left ~/ cellSize; x < right; x++) { + yield (x, y); + } + } + } + + void mark(ui.Rect bounds) { + // The extra paper pixel covers filtered screen pixels just outside the ink. + final dirty = _roundOut(bounds).inflate(1).intersect(visible); + for (final cell in cells(dirty)) { + final (x, y) = cell; + final tile = ui.Rect.fromLTWH( + (x * cellSize).toDouble(), + (y * cellSize).toDouble(), + cellSize.toDouble(), + cellSize.toDouble(), + ); + final part = dirty.intersect(tile); + final patch = patches[cell]; + if (patch == null) { + patches[cell] = _FinePatch(part); + } else { + patch.bounds = patch.bounds.expandToInclude(part); + } + } + } + + Iterable<_FinePatch> plan() { + if (patches.length < 2) return patches.values; + var union = patches.values.first.bounds; + var area = 0.0; + for (final patch in patches.values) { + union = union.expandToInclude(patch.bounds); + area += patch.bounds.width * patch.bounds.height; + } + // CanvasKit synchronizes each readback. Beyond the basic 25% allowance, + // spend up to 64 x 64 extra pixels per readback saved, capped at 50% total. + final extra = math.min(area * .25, (patches.length - 1) * 4096); + if (union.width * union.height <= area * 1.25 + extra && + union.longestSide <= 4096) { + return [_FinePatch(union)]; + } + return patches.values; + } + + Iterable<_FinePatch> candidates(ui.Rect bounds) sync* { + for (final cell in cells(bounds.inflate(1))) { + final patch = patches[cell]; + if (patch != null) yield patch; + } + } +} + +class _FinePatch { + _FinePatch(this.bounds); + + ui.Rect bounds; + late final ui.Rect samples; + late final ui.PictureRecorder recorder; + late final ui.Canvas canvas; + + void begin(ui.Image paper, ui.Rect page) { + // Each patch has its own extra source texel across cell and viewport seams. + samples = bounds.inflate(1).intersect(page); + recorder = ui.PictureRecorder(); + canvas = ui.Canvas(recorder) + ..translate(-samples.left, -samples.top) + ..drawImage(paper, ui.Offset.zero, ui.Paint()); + } + + void draw(ui.Canvas target, ui.Paint display) { + final picture = recorder.endRecording(); + final image = picture.toImageSync( + samples.width.toInt(), + samples.height.toInt(), + ); + picture.dispose(); + target.save(); + target.clipRect(bounds, doAntiAlias: false); + target.drawImage(image, samples.topLeft, display); + target.restore(); + image.dispose(); + } +} + /// The atlas is decoded once while moving glyphs. Clipboard and exports use /// identical integer compositing in page pixels, independent of device zoom. class FineRaster { - FineRaster._(this.paper, this.page, this._pixels, this._width) - : _displayPixels = Uint8List(_pixels.length * 4); + FineRaster._(this.paper, this.page, this._pixels, this._width) { + // Filtered atlas draws may read beyond a source rectangle. Reserve a transparent + // texel around each slot even when the incoming packet packs glyphs edge-to-edge. + _displayWidth = _width + 2; + var x = 0, y = 0, row = 0; + for (final glyph in page.glyphs) { + if (x + glyph.width + 2 > _displayWidth) { + x = 0; + y += row; + row = 0; + } + _slots[glyph.id] = (x: x + 1, y: y + 1); + x += glyph.width + 2; + row = math.max(row, glyph.height + 2); + } + _displayPixels = Uint8List(_displayWidth * math.max(1, y + row) * 4); + } final ui.Image paper; final FinePage page; final Uint8List _pixels; final int _width; - final Uint8List _displayPixels; - final _masks = {}; + late final Uint8List _displayPixels; + late final int _displayWidth; + final _slots = {}; + final _masks = {}; InkLook? _look; ui.Image? _displayAtlas; bool _disposed = false; @@ -123,25 +280,46 @@ class FineRaster { } } - Uint8List _mask(FineGlyph glyph, InkLook look, _Shape shape) { + Uint8List _shapeMask(FineGlyph glyph, _Shape shape) { final mask = Uint8List(glyph.width * glyph.height); for (var y = 0; y < glyph.height; y++) { final start = (glyph.ay + y) * _width + glyph.ax; mask.setRange(y * glyph.width, (y + 1) * glyph.width, _pixels, start); } - final shaped = shapeInkAlpha( + return shapeInkAlpha( (alpha: mask, width: glyph.width, height: glyph.height), shape.thickness, shape.softness, ); + } + + _Mask _mask(FineGlyph glyph, InkLook look, _Shape shape) { + final cached = _masks[glyph.id]; + final base = + cached != null && + cached.shape.thickness == shape.thickness && + cached.shape.softness == shape.softness + ? cached.base + : _shapeMask(glyph, shape); final opacity = look.opacity * (look.color >> 24 & 255); - if (opacity != 25500) { - // The plain mask may be shared. Each glyph has its own alpha buffer. - for (var i = 0; i < shaped.length; i++) { - shaped[i] = (shaped[i] * opacity + 12750) ~/ 25500; + var pixels = base; + if (opacity != 25500 || shape.opacity != 100 || shape.ramp != null) { + pixels = Uint8List(base.length); + for (var y = 0; y < glyph.height; y++) { + var local = shape.opacity; + if (shape.ramp case final r?) { + final position = (y + .5) * 100 / glyph.height; + final t = ((position - r.start) / (r.end - r.start)).clamp(0.0, 1.0); + local = (local * ((r.from + t * (r.to - r.from)) / 100)).round(); + } + for (var x = 0; x < glyph.width; x++) { + final i = y * glyph.width + x; + final alpha = (base[i] * opacity + 12750) ~/ 25500; + pixels[i] = (alpha * local + 50) ~/ 100; + } } } - return shaped; + return (shape: shape, base: base, pixels: pixels); } Future prepare(InkLook look, Map edits) async { @@ -152,20 +330,21 @@ class FineRaster { final shape = _shape(base, edits[glyph.id]); if (!rebuild && _masks[glyph.id]?.shape == shape) continue; final mask = _mask(glyph, base, shape); - _masks[glyph.id] = (shape: shape, pixels: mask); + _masks[glyph.id] = mask; changed = true; + final slot = _slots[glyph.id]!; for (var y = 0; y < glyph.height; y++) { - final start = ((glyph.ay + y) * _width + glyph.ax) * 4; + final start = ((slot.y + y) * _displayWidth + slot.x) * 4; for (var x = 0; x < glyph.width; x++) { - _displayPixels[start + x * 4 + 3] = mask[y * glyph.width + x]; + _displayPixels[start + x * 4 + 3] = mask.pixels[y * glyph.width + x]; } } } if (!changed) return; - final atlas = await _image( + final atlas = await decodeRgbaPixels( _displayPixels, - _width, - _displayPixels.length ~/ (_width * 4), + _displayWidth, + _displayPixels.length ~/ (_displayWidth * 4), ); if (_disposed) { atlas.dispose(); @@ -176,78 +355,156 @@ class FineRaster { _look = look; } - void paint(ui.Canvas canvas, Map edits, InkLook look) { - canvas.drawImage(paper, ui.Offset.zero, ui.Paint()); - final atlas = _displayAtlas; - if (atlas == null) return; - final brush = ui.Paint()..filterQuality = ui.FilterQuality.none; - final paintLook = _look ?? look; - canvas.save(); - canvas.clipRect( - ui.Rect.fromLTWH(0, 0, paper.width.toDouble(), paper.height.toDouble()), + void paint( + ui.Canvas canvas, + Map edits, + InkLook look, { + FineFrame? committed, + }) { + final display = ui.Paint()..filterQuality = ui.FilterQuality.low; + final pageBounds = ui.Rect.fromLTWH( + 0, + 0, + paper.width.toDouble(), + paper.height.toDouble(), ); + final grid = _FinePatchGrid(pageBounds, canvas.getLocalClipBounds()); for (final glyph in page.glyphs) { final edit = edits[glyph.id]; - final pose = FinePose(glyph, edit); - final color = ui.Color(edit?.color ?? fineInkLook(glyph, paintLook).color) - .withValues(alpha: (edit?.opacity ?? 100) / 100); - brush.colorFilter = ui.ColorFilter.mode(color, ui.BlendMode.srcIn); - final w = glyph.width.toDouble(), h = glyph.height.toDouble(); - canvas.save(); - canvas.translate(pose.origin.dx, pose.origin.dy); - if (pose.projection case final m?) { - canvas.transform( - Float64List.fromList([ - m[0], - m[3], - 0, - m[6], - m[1], - m[4], - 0, - m[7], - 0, - 0, - 1, - 0, - m[2], - m[5], - 0, - m[8], - ]), - ); + if (committed != null && + committed.look == look && + committed.edits[glyph.id] == edit) { + continue; + } + grid.mark(FinePose(glyph, edit).paintBounds); + if (committed != null) { + grid.mark(FinePose(glyph, committed.edits[glyph.id]).paintBounds); + } + } + final patches = grid.plan(); + final background = committed?.image ?? paper; + if (patches.isEmpty) { + canvas.drawImage(background, ui.Offset.zero, display); + return; + } + canvas.save(); + for (final patch in patches) { + canvas.clipRect( + patch.bounds, + clipOp: ui.ClipOp.difference, + doAntiAlias: false, + ); + patch.begin(paper, pageBounds); + } + canvas.drawImage(background, ui.Offset.zero, display); + canvas.restore(); + + final atlas = _displayAtlas; + if (atlas != null) { + final brush = ui.Paint()..filterQuality = ui.FilterQuality.low; + final paintLook = _look ?? look; + // Visit glyphs once in stacking order, including unchanged ink that + // overlaps an erased source, a destination or its bilinear sample border. + for (final glyph in page.glyphs) { + final edit = edits[glyph.id]; + final pose = FinePose(glyph, edit); + final candidates = patches.length == 1 + ? patches + : grid.candidates(pose.paintBounds); + for (final patch in candidates) { + if (patch.samples.overlaps(pose.paintBounds)) { + _paintGlyph( + patch.canvas, + atlas, + brush, + glyph, + pose, + edit, + paintLook, + ); + } + } } - canvas.rotate(pose.angle); - canvas.scale(pose.scale); - canvas.drawImageRect( - atlas, - ui.Rect.fromLTWH(glyph.ax.toDouble(), glyph.ay.toDouble(), w, h), - ui.Rect.fromLTWH(-w / 2, -h / 2, w, h), - brush, + } + for (final patch in patches) { + patch.draw(canvas, display); + } + } + + void _paintGlyph( + ui.Canvas canvas, + ui.Image atlas, + ui.Paint brush, + FineGlyph glyph, + FinePose pose, + FineAdjustment? edit, + InkLook paintLook, + ) { + final color = ui.Color(edit?.color ?? fineInkLook(glyph, paintLook).color) + .withValues(alpha: 1); + brush.colorFilter = ui.ColorFilter.mode(color, ui.BlendMode.srcIn); + final w = glyph.width.toDouble(), h = glyph.height.toDouble(); + canvas.save(); + canvas.clipRect(pose.paintBounds, doAntiAlias: false); + canvas.translate(pose.origin.dx, pose.origin.dy); + if (pose.projection case final m?) { + canvas.transform( + Float64List.fromList([ + m[0], + m[3], + 0, + m[6], + m[1], + m[4], + 0, + m[7], + 0, + 0, + 1, + 0, + m[2], + m[5], + 0, + m[8], + ]), ); - canvas.restore(); } + canvas.rotate(pose.angle); + canvas.scale(pose.scale); + final slot = _slots[glyph.id]!; + final dest = ui.Rect.fromLTWH(-w / 2, -h / 2, w, h); + canvas.drawImageRect( + atlas, + ui.Rect.fromLTWH(slot.x.toDouble(), slot.y.toDouble(), w, h).inflate(1), + dest.inflate(1), + brush, + ); canvas.restore(); } - Future render(Map edits, InkLook look) async { + Future _compose( + Map edits, + InkLook look, + ) async { final width = paper.width, height = paper.height; - final data = (await paper.toByteData(format: ui.ImageByteFormat.rawRgba))!; + final data = (await paper.toByteData( + format: ui.ImageByteFormat.rawStraightRgba, + ))!; final pixels = data.buffer.asUint8List(); for (final glyph in page.glyphs) { final edit = edits[glyph.id]; final pose = FinePose(glyph, edit); - final rect = pose.bounds; + final rect = pose.paintBounds; final left = math.max(0, rect.left.floor()); final right = math.min(width, rect.right.ceil()); final baseLook = fineInkLook(glyph, look); final color = edit?.color ?? baseLook.color; - final opacity = edit?.opacity ?? 100; + final aligned = pose.aligned; final shape = _shape(baseLook, edit); final cached = _masks[glyph.id]; final mask = _look == look && cached?.shape == shape ? cached!.pixels - : _mask(glyph, baseLook, shape); + : _mask(glyph, baseLook, shape).pixels; for ( var y = math.max(0, rect.top.floor()); y < math.min(height, rect.bottom.ceil()); @@ -261,43 +518,51 @@ class FineRaster { } final dx = position.dx, dy = position.dy; final sx = - ((dx * pose.cos + dy * pose.sin) / pose.scale + - glyph.width / 2 + - 1e-9) - .floor(); + (dx * pose.cos + dy * pose.sin) / pose.scale + glyph.width / 2; final sy = - ((-dx * pose.sin + dy * pose.cos) / pose.scale + - glyph.height / 2 + - 1e-9) - .floor(); - if (sx < 0 || sy < 0 || sx >= glyph.width || sy >= glyph.height) { + (-dx * pose.sin + dy * pose.cos) / pose.scale + glyph.height / 2; + if (sx <= -.5 || + sy <= -.5 || + sx >= glyph.width + .5 || + sy >= glyph.height + .5) { continue; } - final alpha = (mask[sy * glyph.width + sx] * opacity + 50) ~/ 100; + final alpha = aligned + ? mask[sy.toInt() * glyph.width + sx.toInt()] + : _sample(mask, glyph.width, glyph.height, sx - .5, sy - .5); if (alpha == 0) continue; final base = (y * width + x) * 4; - // rawRgba stores premultiplied RGB; source-over also updates alpha. - pixels[base + 3] = - alpha + (pixels[base + 3] * (255 - alpha) + 127) ~/ 255; + final dest = pixels[base + 3] * (255 - alpha); + final source = alpha * 255; + final total = source + dest; for (var c = 0; c < 3; c++) { final value = color >> ((2 - c) * 8) & 255; pixels[base + c] = - (pixels[base + c] * (255 - alpha) + value * alpha + 127) ~/ 255; + (pixels[base + c] * dest + value * source + total ~/ 2) ~/ + total; } + pixels[base + 3] = (total + 127) ~/ 255; } } } - return _image(pixels, width, height); + return pixels; } - Future png(Map edits, InkLook look) async { - final image = await render(edits, look); - try { - return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer - .asUint8List(); - } finally { - image.dispose(); + Future render(Map edits, InkLook look) async { + final pixels = await _compose(edits, look); + for (var i = 0; i < pixels.length; i += 4) { + final alpha = pixels[i + 3]; + if (alpha == 255) continue; + for (var c = 0; c < 3; c++) { + pixels[i + c] = (pixels[i + c] * alpha + 127) ~/ 255; + } } + return decodeRgbaPixels(pixels, paper.width, paper.height); + } + + Future png(Map edits, InkLook look) async { + final pixels = await _compose(edits, look); + return encodePagePng(pixels, paper.width, paper.height); } void dispose() { diff --git a/app/lib/utils/ink_effects.dart b/app/lib/utils/ink_effects.dart index 95bfc886..9718de0d 100644 --- a/app/lib/utils/ink_effects.dart +++ b/app/lib/utils/ink_effects.dart @@ -1,7 +1,7 @@ -import 'dart:async'; import 'dart:ui' as ui; import 'paper_exif.dart'; +import 'rgba_png.dart'; import 'package:flutter/foundation.dart'; @@ -116,51 +116,60 @@ Future shapeInk(InkMask source, InkLook look) async { thickness: look.thickness, softness: look.softness, )); - final result = Completer(); - ui.decodeImageFromPixels( - bytes, - source.width, - source.height, - ui.PixelFormat.rgba8888, - result.complete, - ); - return result.future; + return decodeRgbaPixels(bytes, source.width, source.height); +} + +typedef _CompositeJob = ({ + Uint8List paper, + int width, + InkMask ink, + InkLook look, +}); + +Uint8List _compositeInk(_CompositeJob job) { + final pixels = job.paper; + final look = job.look; + final mask = shapeInkAlpha(job.ink, look.thickness, look.softness); + final strength = look.opacity * (look.color >> 24 & 255); + final red = look.color >> 16 & 255, + green = look.color >> 8 & 255, + blue = look.color & 255; + final height = pixels.length ~/ (job.width * 4); + for (var y = 0; y < height && y < job.ink.height; y++) { + for (var x = 0; x < job.width && x < job.ink.width; x++) { + final alpha = (mask[y * job.ink.width + x] * strength + 12750) ~/ 25500; + if (alpha == 0) continue; + final i = (y * job.width + x) * 4; + final dest = pixels[i + 3] * (255 - alpha); + final source = alpha * 255; + final total = source + dest; + int blend(int under, int over) => + (under * dest + over * source + total ~/ 2) ~/ total; + pixels[i] = blend(pixels[i], red); + pixels[i + 1] = blend(pixels[i + 1], green); + pixels[i + 2] = blend(pixels[i + 2], blue); + pixels[i + 3] = (total + 127) ~/ 255; + } + } + return pixels; } Future compositeInkPage(InkPage page, InkLook look) async { final paper = await decodeInkImage(page.paper); try { - final ink = await shapeInk(await decodeInkMask(page.ink!), look); - try { - final recorder = ui.PictureRecorder(); - final canvas = ui.Canvas(recorder); - canvas.drawImage(paper, ui.Offset.zero, ui.Paint()); - canvas.drawImage( - ink, - ui.Offset.zero, - ui.Paint() - ..colorFilter = ui.ColorFilter.mode( - composeInkColor(look), - ui.BlendMode.srcIn, - ), - ); - final picture = recorder.endRecording(); - try { - final rendered = await picture.toImage(paper.width, paper.height); - try { - final png = (await rendered.toByteData( - format: ui.ImageByteFormat.png, - ))!; - return withPaperExif(Uint8List.sublistView(png), page.cameraExif); - } finally { - rendered.dispose(); - } - } finally { - picture.dispose(); - } - } finally { - ink.dispose(); - } + final data = (await paper.toByteData( + format: ui.ImageByteFormat.rawStraightRgba, + ))!; + final pixels = await compute(_compositeInk, ( + paper: Uint8List.sublistView(data), + width: paper.width, + ink: await decodeInkMask(page.ink!), + look: look, + )); + return withPaperExif( + await encodePagePng(pixels, paper.width, paper.height), + page.cameraExif, + ); } finally { paper.dispose(); } diff --git a/app/lib/utils/rgba_png.dart b/app/lib/utils/rgba_png.dart new file mode 100644 index 00000000..3d71e6bd --- /dev/null +++ b/app/lib/utils/rgba_png.dart @@ -0,0 +1,52 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart' show compute; +import 'package:image/image.dart' as img; + +Uint8List _encodeStraightPng( + ({Uint8List pixels, int width, int height}) page, +) => img.encodePng( + img.Image.fromBytes( + width: page.width, + height: page.height, + bytes: page.pixels.buffer, + bytesOffset: page.pixels.offsetInBytes, + numChannels: 4, + ), + level: 1, +); + +/// Keep the pen color at low alpha. Opaque pages can use the native PNG encoder. +Future encodePagePng(Uint8List pixels, int width, int height) async { + for (var i = 3; i < pixels.length; i += 4) { + if (pixels[i] < 255) { + // Keep straight RGB even for near-transparent color that a display image cannot encode. + return compute(_encodeStraightPng, ( + pixels: pixels, + width: width, + height: height, + )); + } + } + final image = await decodeRgbaPixels(pixels, width, height); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer + .asUint8List(); + } finally { + image.dispose(); + } +} + +Future decodeRgbaPixels(Uint8List pixels, int width, int height) { + final result = Completer(); + ui.decodeImageFromPixels( + pixels, + width, + height, + ui.PixelFormat.rgba8888, + result.complete, + ); + return result.future; +} diff --git a/app/lib/view_models/fine_selection.dart b/app/lib/view_models/fine_selection.dart index 3fec630b..c6e6af4f 100644 --- a/app/lib/view_models/fine_selection.dart +++ b/app/lib/view_models/fine_selection.dart @@ -215,6 +215,7 @@ class FineSelection { scale: edit.scale, angle: edit.angle, opacity: edit.opacity, + opacityRamp: edit.opacityRamp, color: edit.color, thickness: edit.thickness, softness: edit.softness, @@ -282,6 +283,7 @@ class FineSelection { scale: v.scale, angle: v.angle, opacity: v.opacity, + opacityRamp: v.opacityRamp, color: v.color, thickness: v.thickness, softness: v.softness, @@ -307,6 +309,7 @@ class FineSelection { scale: scale ?? v.scale, angle: angle ?? v.angle, opacity: opacity ?? v.opacity, + opacityRamp: v.opacityRamp, color: color ?? v.color, thickness: thickness ?? v.thickness, softness: softness ?? v.softness, diff --git a/app/lib/widgets/fine_preview.dart b/app/lib/widgets/fine_preview.dart index 64bd08ff..beb16da4 100644 --- a/app/lib/widgets/fine_preview.dart +++ b/app/lib/widgets/fine_preview.dart @@ -84,7 +84,7 @@ class _FinePreviewState extends State { final _zoom = TransformationController(); FinePage get model => widget.page.fine!; FineRaster? _raster; - ui.Image? _committed; + FineFrame? _committed; FineSelectionDrag? _gesture; FineCornerDrag? _cornerDrag; List? get _corners => _selection.tool != FineTool.perspective @@ -173,9 +173,9 @@ class _FinePreviewState extends State { image.dispose(); return; } - final old = _committed; + final old = _committed?.image; setState(() { - _committed = image; + _committed = (image: image, edits: edits, look: look); _failed = false; _awaitingPixels = _pending; }); @@ -202,7 +202,7 @@ class _FinePreviewState extends State { _focus.dispose(); _zoom.dispose(); _raster?.dispose(); - _committed?.dispose(); + _committed?.image.dispose(); for (final image in _retired) { image.dispose(); } @@ -407,7 +407,8 @@ class _FinePreviewState extends State { int? thickness, int? softness, }) { - final changesShape = thickness != null || softness != null; + final changesShape = + thickness != null || softness != null || opacity != null; setState(() { _shapeDraft = changesShape; _draft = _selection.adjust( @@ -600,9 +601,9 @@ class _FinePreviewState extends State { Widget _paper(BuildContext context) { final l = AppLocalizations.of(context)!; final raster = _raster; - final image = _committed; + final frame = _committed; if (_failed) return Center(child: Text(l.fineUnavailable)); - if (raster == null || image == null) { + if (raster == null || frame == null) { return const Center(child: CircularProgressIndicator()); } final color = Theme.of(context).colorScheme.primary; @@ -615,6 +616,7 @@ class _FinePreviewState extends State { if (fit <= 0 || !fit.isFinite) return const SizedBox.shrink(); _updateViewport(bounds.biggest, fit); _scheduleDefaultZoom(); + final visible = _visible; final surface = SizedBox.fromSize( size: _size * fit, child: PreviewImageActions( @@ -633,9 +635,9 @@ class _FinePreviewState extends State { child: CustomPaint( painter: FinePreviewPainter( raster, - image, + frame, widget.look, - _visible, + visible, draft: _draft.isNotEmpty || _awaitingPixels, corners: widget.editing ? _corners : null, handleScale: _zoom.value.getMaxScaleOnAxis(), @@ -645,7 +647,7 @@ class _FinePreviewState extends State { for (final glyph in model.glyphs.where( (glyph) => _selection.selected.contains(glyph.id), )) - FinePose(glyph, _visible[glyph.id]).bounds, + FinePose(glyph, visible[glyph.id]).bounds, } : {}, box: _gesture?.box, diff --git a/app/lib/widgets/fine_preview_painter.dart b/app/lib/widgets/fine_preview_painter.dart index 7f2ae4f9..146b1db7 100644 --- a/app/lib/widgets/fine_preview_painter.dart +++ b/app/lib/widgets/fine_preview_painter.dart @@ -1,5 +1,3 @@ -import 'dart:ui' as ui; - import 'package:flutter/material.dart'; import '../models/fine_edit.dart'; @@ -10,7 +8,7 @@ import '../utils/fine_raster.dart'; class FinePreviewPainter extends CustomPainter { FinePreviewPainter( this.raster, - this.image, + this.frame, this.look, this.edits, { required this.draft, @@ -22,7 +20,7 @@ class FinePreviewPainter extends CustomPainter { required this.color, }); final FineRaster raster; - final ui.Image image; + final FineFrame frame; final InkLook look; final Map edits; final bool draft; @@ -36,13 +34,13 @@ class FinePreviewPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { canvas.save(); - final fit = size.width / image.width; + final fit = size.width / frame.image.width; canvas.scale(fit); if (draft) { - raster.paint(canvas, edits, look); + raster.paint(canvas, edits, look, committed: frame); } else { canvas.drawImage( - image, + frame.image, Offset.zero, Paint()..filterQuality = FilterQuality.low, ); diff --git a/app/test/fine_draft_test.dart b/app/test/fine_draft_test.dart new file mode 100644 index 00000000..b145b9e6 --- /dev/null +++ b/app/test/fine_draft_test.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/services/fine_draft.dart'; + +void main() { + final current = '4' * 64; + final legacy = '3' * 64; + final ramp = [ + [15, 20], + [75, 85], + ]; + final common = [ + for (var id = 1; id <= 3; id++) + { + 'id': id, + 'dx': id, + 'dy': -3, + 'scale': 93, + 'angle': 13, + 'opacity': 74, + 'color': [120, 60, 30], + }, + ]; + final parsed = FineEdits.fromJson({ + 'key': current, + 'glyphs': [ + for (final row in common) {...row, 'opacity_ramp': ramp}, + ], + }); + final draft = FineDraft.encode( + FineEdits(current, parsed.glyphs, rollbackKey: legacy), + ); + + test( + 'a legacy save can reopen the complete current layout and gradients', + () { + expect(draft.edits['key'], legacy); + final restored = FineDraft.read({ + 'key': legacy, + 'glyphs': common, + }, draft.extension)!; + expect(restored.key, current); + expect(restored.rollbackKey, legacy); + expect(restored.glyphs, parsed.glyphs); + expect(FineDraft.read(draft.edits, 'damaged')!.glyphs, parsed.glyphs); + expect(FineDraft.read(draft.edits, null)!.key, current); + }, + ); + + test( + 'older edits retain their own layout, changed fields, and deletions', + () { + final restored = FineDraft.read({ + 'key': legacy, + 'glyphs': [ + common.first, + {...common[1], 'dx': 54}, + {...common.last, 'id': 4}, + ], + }, draft.extension)!; + expect(restored.key, legacy); + expect(restored.rollbackKey, isNull); + expect(restored.glyphs.keys, [1, 2, 4]); + expect(restored.glyphs[1], parsed.glyphs[1]); + expect(restored.glyphs[2]!.dx, 54); + expect(restored.glyphs[2]!.opacityRamp, isNull); + expect(restored.glyphs[4]!.opacityRamp, isNull); + }, + ); + + test( + 'invalid or unrelated recovery metadata preserves readable legacy fields', + () { + for (final bad in [ + '{', + draft.extension!.replaceFirst(current, 'a${current.substring(1)}'), + draft.extension!.replaceFirst('[[15,20]', '[[15,21]'), + '[]', + jsonEncode({'key': current}), + jsonEncode({...jsonDecode(draft.extension!) as Map, 'layoutKey': 1}), + jsonEncode({...jsonDecode(draft.extension!) as Map, 'ramps': []}), + ]) { + final restored = FineDraft.read({ + 'key': legacy, + 'glyphs': common, + }, bad)!; + expect(restored.key, legacy); + expect(restored.glyphs[1]!.dx, 1); + expect(restored.glyphs[1]!.opacityRamp, isNull); + } + final different = FineDraft.read({ + 'key': '2' * 64, + 'glyphs': common, + }, draft.extension)!; + expect(different.key, '2' * 64); + expect(different.glyphs[1]!.opacityRamp, isNull); + }, + ); +} diff --git a/app/test/fine_edit_history_test.dart b/app/test/fine_edit_history_test.dart index bb25c26f..4c719b22 100644 --- a/app/test/fine_edit_history_test.dart +++ b/app/test/fine_edit_history_test.dart @@ -12,6 +12,7 @@ FineAdjustment moved(int id, int dx) => ( color: null, thickness: 0, softness: 0, + opacityRamp: null, warp: null, ); diff --git a/app/test/fine_preview_test.dart b/app/test/fine_preview_test.dart index 3386a58d..dc3873c4 100644 --- a/app/test/fine_preview_test.dart +++ b/app/test/fine_preview_test.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart' show StandardMessageCodec; import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; import 'package:handwriting_app/l10n/app_localizations.dart'; import 'package:handwriting_app/main.dart'; import 'package:handwriting_app/models/fine_edit.dart'; @@ -92,6 +93,7 @@ void main() { thickness: 0, softness: 0, color: null, + opacityRamp: null, warp: null, ), ]); @@ -135,6 +137,197 @@ void main() { expect(blur.valid, isFalse); }); + testWidgets( + 'live filtering, copy and saved ramps sample only their atlas tile', + (tester) async { + await tester.runAsync(() async { + final atlas = img.Image(width: 4, height: 2, numChannels: 4); + const rows = [ + [255, 127, 255, 255], + [10, 200, 255, 255], + ]; + for (var y = 0; y < 2; y++) { + for (var x = 0; x < 4; x++) { + atlas.setPixelRgba(x, y, rows[y][x], 0, 0, 255); + } + } + final page = InkPage( + img.encodePng(img.Image(width: 10, height: 10, numChannels: 4)), + null, + fine: FinePage('0' * 64, img.encodePng(atlas), const [ + FineGlyph(1, 4, 4, 2, 2, 0, 0, 6, null), + FineGlyph(2, 0, 0, 2, 2, 2, 0, 2, null), + ]), + ); + final raster = await FineRaster.decode(page); + try { + final plain = img.decodePng(await raster.png({}, defaultInkLook))!; + expect( + [ + for (var y = 4; y < 6; y++) + for (var x = 4; x < 6; x++) plain.getPixel(x, y).a, + ], + [255, 127, 10, 200], + ); + const look = ( + opacity: 80, + thickness: 0.0, + softness: 0.0, + color: 0xc8296ac9, + ); + final saved = FineEdits.fromJson({ + 'key': page.fine!.key, + 'glyphs': [ + { + 'id': 1, + 'dx': 0, + 'dy': 0, + 'scale': 100, + 'angle': 0, + 'opacity': 80, + 'opacity_ramp': [ + [0, 0], + [100, 100], + ], + 'warp': [1, 0, .5, 0, 1, 0, 0, 0], + }, + ], + }); + expect(FineEdits.fromJson(saved.toJson()).glyphs, saved.glyphs); + await raster.prepare(look, saved.glyphs); + final copied = img.decodePng(await raster.png(saved.glyphs, look))!; + final recorder = ui.PictureRecorder(); + raster.paint(Canvas(recorder), saved.glyphs, look); + final picture = recorder.endRecording(); + final preview = await picture.toImage(10, 10); + try { + final raw = (await preview.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + const expected = [ + [16, 24, 8, 0], + [2, 40, 38, 0], + ]; + for (var y = 0; y < 2; y++) { + for (var x = 0; x < 4; x++) { + final alpha = expected[y][x]; + final pixel = copied.getPixel(4 + x, 4 + y); + expect(pixel.a, alpha); + if (alpha != 0) { + expect([pixel.r, pixel.g, pixel.b], [41, 106, 201]); + } + expect( + raw.getUint8(((4 + y) * 10 + 4 + x) * 4 + 3), + closeTo(alpha, 1), + ); + } + } + } finally { + preview.dispose(); + picture.dispose(); + } + } finally { + raster.dispose(); + } + }); + }, + ); + + testWidgets('zoomed drag and committed ink use the same paper pixels', ( + tester, + ) async { + await tester.runAsync(() async { + final atlas = img.Image(width: 9, height: 5, numChannels: 4); + for (var y = 1; y < 4; y++) { + for (final x in [1, 4, 7]) { + atlas.setPixelRgba(x, y, 255, 0, 0, 255); + } + } + final page = InkPage( + img.encodePng(img.Image(width: 24, height: 12, numChannels: 4)), + null, + fine: FinePage('0' * 64, img.encodePng(atlas), const [ + FineGlyph(1, 4, 3, 3, 5, 0, 0, 7, null), + FineGlyph(2, 7, 3, 3, 5, 3, 0, 7, null), + FineGlyph(3, 19, 3, 3, 5, 6, 0, 7, null), + ]), + ); + final raster = await FineRaster.decode(page); + final edits = FineEdits.fromJson({ + 'key': page.fine!.key, + 'glyphs': [ + { + 'id': 1, + 'dx': 2, + 'dy': 0, + 'scale': 100, + 'angle': 0, + 'opacity': 80, + 'warp': [1, 0, .5, 0, 1, 0, 0, 0], + }, + ], + }).glyphs; + const originalEdits = {}; + await raster.prepare(defaultInkLook, originalEdits); + final original = await raster.render(originalEdits, defaultInkLook); + await raster.prepare(defaultInkLook, edits); + final finalImage = await raster.render(edits, defaultInkLook); + try { + for (final scale in [.6, 1.0, 1.75, 2.0, 4.0]) { + Future pixels({required bool dragging}) async { + final recorder = ui.PictureRecorder(); + final canvas = Canvas(recorder) + ..translate(.25, .5) + ..scale(scale); + if (dragging) { + raster.paint( + canvas, + edits, + defaultInkLook, + committed: ( + image: original, + edits: originalEdits, + look: defaultInkLook, + ), + ); + } else { + canvas.drawImage( + finalImage, + Offset.zero, + Paint()..filterQuality = FilterQuality.low, + ); + } + final picture = recorder.endRecording(); + final image = await picture.toImage( + (24 * scale + 1).ceil(), + (12 * scale + 1).ceil(), + ); + try { + return (await image.toByteData())!.buffer.asUint8List(); + } finally { + picture.dispose(); + image.dispose(); + } + } + + final actual = await pixels(dragging: true); + final expected = await pixels(dragging: false); + for (var i = 3; i < actual.length; i += 4) { + expect( + actual[i], + closeTo(expected[i], 1), + reason: 'zoom $scale, byte $i', + ); + } + } + } finally { + original.dispose(); + finalImage.dispose(); + raster.dispose(); + } + }); + }); + testWidgets( 'saving a fine page preserves transparent paper and translucent ink', (tester) async { diff --git a/app/test/fine_raster_patches_test.dart b/app/test/fine_raster_patches_test.dart new file mode 100644 index 00000000..7b52934d --- /dev/null +++ b/app/test/fine_raster_patches_test.dart @@ -0,0 +1,316 @@ +import 'dart:typed_data'; +import 'dart:ui' as ui; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:handwriting_app/models/fine_edit.dart'; +import 'package:handwriting_app/models/ink_page.dart'; +import 'package:handwriting_app/utils/fine_raster.dart'; +import 'package:handwriting_app/view_models/fine_selection.dart'; +import 'package:image/image.dart' as img; + +class _PatchCanvas extends TestRecordingCanvas { + _PatchCanvas(this.background, this.viewport); + + final ui.Image background; + final ui.Rect viewport; + final patches = []; + + @override + ui.Rect getLocalClipBounds() => viewport; + + @override + void drawImage(ui.Image image, ui.Offset offset, ui.Paint paint) { + if (!identical(image, background)) { + patches.add( + offset & ui.Size(image.width.toDouble(), image.height.toDouble()), + ); + } + } +} + +void main() { + testWidgets( + 'sparse draft allocates only visible source and destination ink', + (tester) async { + await tester.runAsync(() async { + const width = 1200, height = 1800; + final glyphs = [ + for (var row = 0; row < 40; row++) + for (var col = 0; col < 30; col++) + FineGlyph( + row * 30 + col, + 10 + col * 40, + 10 + row * 45, + 12, + 12, + 0, + 0, + 0, + null, + ), + ]; + final atlas = img.Image(width: 12, height: 12) + ..clear(img.ColorRgb8(255, 0, 0)); + final page = InkPage( + img.encodePng( + img.Image(width: width, height: height, numChannels: 4), + ), + null, + fine: FinePage('0' * 64, img.encodePng(atlas), glyphs), + ); + final raster = await FineRaster.decode(page); + const look = defaultInkLook; + await raster.prepare(look, {}); + final image = await raster.render({}, look); + try { + final edits = FineEdits.fromJson({ + 'key': page.fine!.key, + 'glyphs': [ + for (final (id, dx, dy) in [(0, 6, 5), (1199, -600, -890)]) + { + 'id': id, + 'dx': dx, + 'dy': dy, + 'angle': 0, + 'scale': 100, + 'opacity': 100, + }, + ], + }).glyphs; + List paint( + ui.Rect viewport, + Map values, + ) { + final canvas = _PatchCanvas(image, viewport); + raster.paint( + canvas, + values, + look, + committed: (image: image, edits: {}, look: look), + ); + return canvas.patches; + } + + const full = ui.Rect.fromLTWH(0, 0, 1200, 1800); + final patches = paint(full, edits); + final pixels = patches.fold( + 0, + (n, r) => n + (r.width * r.height).toInt(), + ); + expect( + pixels, + lessThan(1500), + reason: 'temporary paper-resolution pixels: $pixels in $patches', + ); + expect(patches, hasLength(3)); + expect( + paint(const ui.Rect.fromLTWH(400, 600, 360, 360), edits), + hasLength(1), + ); + expect( + paint(const ui.Rect.fromLTWH(800, 200, 200, 400), edits), + isEmpty, + ); + final dense = paint(full, { + for (final g in glyphs) g.id: defaultFineAdjustment(g.id), + }); + expect(dense, hasLength(1)); + expect(full.contains(dense.single.topLeft), isTrue); + expect(full.contains(dense.single.bottomRight), isTrue); + final near = paint(full, {0: edits[0]!}); + expect(near, hasLength(1)); + expect(near.single.width * near.single.height, lessThan(500)); + final selection = FineSelection()..select([0, 1199]); + final drag = selection.move( + page.fine!, + {}, + const ui.Offset(6, 5), + full.size, + snapToLine: false, + ); + final distant = paint(full, {for (final edit in drag) edit.id: edit}); + expect(distant, hasLength(2)); + expect(distant.every((r) => r.width * r.height < 500), isTrue); + } finally { + image.dispose(); + raster.dispose(); + } + }); + }, + ); + testWidgets('dense drag keeps one readback across cell boundaries', ( + tester, + ) async { + await tester.runAsync(() async { + const width = 1654, height = 2339; + final glyphs = [ + for (var id = 0; id < 750; id++) + FineGlyph( + id, + 36 + id % 25 * 64, + 36 + id ~/ 25 * 76, + 24, + 24, + 0, + 0, + 0, + null, + ), + ]; + final page = InkPage( + img.encodePng(img.Image(width: width, height: height)), + null, + fine: FinePage( + '0' * 64, + img.encodePng(img.Image(width: 24, height: 24)), + glyphs, + ), + ); + final raster = await FineRaster.decode(page); + try { + final selection = FineSelection()..select(List.generate(512, (i) => i)); + const viewport = ui.Rect.fromLTWH(0, 0, 1654, 2339); + // Replay a full period of both the horizontal and vertical drag offsets. + for (var frame = 0; frame < 19 * 9; frame++) { + final delta = ui.Offset(2.0 + frame % 19, 4.0 + frame % 9); + final edits = selection.move( + page.fine!, + {}, + delta, + viewport.size, + snapToLine: false, + ); + final canvas = _PatchCanvas(raster.paper, viewport); + raster.paint( + canvas, + {for (final edit in edits) edit.id: edit}, + defaultInkLook, + committed: (image: raster.paper, edits: {}, look: defaultInkLook), + ); + expect( + canvas.patches, + hasLength(1), + reason: 'frame $frame, delta $delta', + ); + } + } finally { + raster.dispose(); + } + }); + }); + testWidgets('filtered patch seams preserve overlap and transparent paper', ( + tester, + ) async { + await tester.runAsync(() async { + const width = 540, height = 36; + final atlas = img.Image(width: 12, height: 12); + for (var y = 0; y < atlas.height; y++) { + for (var x = 0; x < atlas.width; x++) { + atlas.setPixelRgb(x, y, (x * 27 + y * 11) % 256, 0, 0); + } + } + final page = InkPage( + img.encodePng(img.Image(width: width, height: height, numChannels: 4)), + null, + fine: FinePage('0' * 64, img.encodePng(atlas), const [ + FineGlyph(0, 251, 8, 12, 12, 0, 0, 0, null), + FineGlyph(1, 240, 9, 12, 12, 0, 0, 0, null), + FineGlyph(2, 512, 8, 12, 12, 0, 0, 0, null), + FineGlyph(3, 534, 10, 12, 12, 0, 0, 0, null), + ]), + ); + final raster = await FineRaster.decode(page); + Map edits(int delta, int alpha) => + FineEdits.fromJson({ + 'key': page.fine!.key, + 'glyphs': [ + { + 'id': 0, + 'dx': 0, + 'dy': 0, + 'scale': 100, + 'angle': 0, + 'opacity': 100, + 'color': [190, 64, 20], + }, + { + 'id': 1, + 'dx': delta, + 'dy': 0, + 'scale': 100, + 'angle': 0, + 'opacity': alpha, + 'color': [0, 110, 160], + }, + { + 'id': 2, + 'dx': delta, + 'dy': 2, + 'scale': 100, + 'angle': 0, + 'opacity': alpha, + 'warp': [1, 0, .5, 0, 1, 0, 0, 0], + }, + ], + }).glyphs; + final before = edits(-5, 54), after = edits(14, 82); + const look = defaultInkLook; + await raster.prepare(look, before); + final original = await raster.render(before, look); + await raster.prepare(look, after); + final committed = await raster.render(after, look); + try { + for (final scale in [.6, 1.0, 1.75, 4.0]) { + for (final left in [0.0, 250.0, 515.0]) { + Future pixels(bool draft) async { + final recorder = ui.PictureRecorder(); + final canvas = ui.Canvas(recorder) + ..drawColor(const ui.Color(0xffdedede), ui.BlendMode.src) + ..clipRect(const ui.Rect.fromLTWH(0, 0, 330, 112)) + ..translate(.25 - left * scale, .5) + ..scale(scale); + if (draft) { + raster.paint( + canvas, + after, + look, + committed: (image: original, edits: before, look: look), + ); + } else { + canvas.drawImage( + committed, + ui.Offset.zero, + ui.Paint()..filterQuality = ui.FilterQuality.low, + ); + } + final picture = recorder.endRecording(); + final image = await picture.toImage(330, 112); + try { + return (await image.toByteData())!.buffer.asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + } + + final live = await pixels(true), released = await pixels(false); + var maxDelta = 0; + for (var i = 0; i < live.length; i++) { + final delta = (live[i] - released[i]).abs(); + if (delta > maxDelta) maxDelta = delta; + } + expect( + maxDelta, + lessThanOrEqualTo(1), + reason: 'zoom $scale, viewport x=$left', + ); + } + } + } finally { + original.dispose(); + committed.dispose(); + raster.dispose(); + } + }); + }); +} diff --git a/app/test/fine_selection_test.dart b/app/test/fine_selection_test.dart index 3379704b..01b278b0 100644 --- a/app/test/fine_selection_test.dart +++ b/app/test/fine_selection_test.dart @@ -40,6 +40,7 @@ void main() { color: 0xff336699, thickness: 1, softness: 2, + opacityRamp: null, warp: (1.0, 0.1, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0), ); final edits = { @@ -59,6 +60,7 @@ void main() { color: null, thickness: -2, softness: 0, + opacityRamp: null, warp: null, )); expect(changed.last, ( @@ -71,6 +73,7 @@ void main() { color: 0xff336699, thickness: -2, softness: 2, + opacityRamp: null, warp: previous.warp, )); expect(edits, {7: previous, 8: defaultFineAdjustment(8)}); diff --git a/app/test/ink_preview_test.dart b/app/test/ink_preview_test.dart index 3d53d029..332cb3f7 100644 --- a/app/test/ink_preview_test.dart +++ b/app/test/ink_preview_test.dart @@ -4,9 +4,11 @@ import 'dart:ui' as ui; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; import 'package:handwriting_app/l10n/app_localizations.dart'; import 'package:handwriting_app/models/ink_page.dart'; -import 'package:handwriting_app/utils/ink_effects.dart' show decodeInkImage; +import 'package:handwriting_app/utils/ink_effects.dart' + show compositeInkPage, decodeInkImage; import 'package:handwriting_app/widgets/workbench_preview.dart'; Future png(void Function(Canvas) draw) async { @@ -24,6 +26,27 @@ Future png(void Function(Canvas) draw) async { } void main() { + test('ordinary transparent copies preserve tint at each coverage', () async { + TestWidgetsFlutterBinding.ensureInitialized(); + final mask = img.Image(width: 256, height: 1, numChannels: 4); + for (var x = 0; x < mask.width; x++) { + mask.setPixelRgba(x, 0, 0, 0, 0, x); + } + final paper = img.Image(width: mask.width, height: 1, numChannels: 4); + final bytes = await compositeInkPage( + InkPage(img.encodePng(paper), img.encodePng(mask)), + (opacity: 83, thickness: 0.0, softness: 0.0, color: 0xc5296ac9), + ); + final copied = img.decodePng(bytes)!; + for (var x = 0; x < mask.width; x++) { + final alpha = (x * 83 * 197 + 12750) ~/ 25500; + expect( + copied.getPixel(x, 0).toList(), + alpha == 0 ? [0, 0, 0, 0] : [41, 106, 201, alpha], + ); + } + }); + testWidgets('press-and-drag reshapes and recolors only the ink image', ( tester, ) async { diff --git a/app/test/live_api_test.dart b/app/test/live_api_test.dart index 5f5fe5e9..7200f56a 100644 --- a/app/test/live_api_test.dart +++ b/app/test/live_api_test.dart @@ -2,7 +2,9 @@ import 'dart:convert'; import 'dart:io'; import 'dart:ui' as ui; +import 'package:archive/archive.dart' show ZipDecoder; import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; import 'package:handwriting_app/models/settings.dart'; import 'package:handwriting_app/services/api.dart'; import 'package:handwriting_app/services/workspace.dart'; @@ -66,7 +68,7 @@ void main() { : false, ); test( - 'Rust exports the exact pixels from the Flutter fine-edit compositor', + 'Rust exports the exact pixels from ordinary and fine-edit Flutter copies', () async { TestWidgetsFlutterBinding.ensureInitialized(); HttpOverrides.global = null; @@ -89,6 +91,25 @@ void main() { 'ink_thickness': '0.3', 'ink_softness': '0.8', }); + w.settings + ..transparentBackground = true + ..fill = '(41, 106, 201, 197)'; + expect(await w.generate(), isTrue, reason: w.error); + expect(w.inkPages.single!.fine, isNull); + final ordinary = img.decodePng(await w.currentPreviewImage())!; + expect(ordinary.getPixel(0, 0).a, 0); + expect(ordinary.any((pixel) => pixel.a > 0 && pixel.a < 128), isTrue); + expect(await w.generate(preview: false), isTrue, reason: w.error); + final ordinaryZip = ZipDecoder().decodeBytes(w.exportBytes!); + final ordinaryPng = img.decodePng( + ordinaryZip.findFile('0.png')!.content, + )!; + expect( + ordinary.getBytes(order: img.ChannelOrder.rgba), + orderedEquals(ordinaryPng.getBytes(order: img.ChannelOrder.rgba)), + ); + + w.settings.transparentBackground = false; expect(await w.enterFineEdit(), isTrue, reason: w.error); final page = w.inkPages.single!; final model = page.fine!; @@ -102,6 +123,7 @@ void main() { opacity: 72, color: 0xff1240d0, thickness: 7, + opacityRamp: (start: 15, from: 33, end: 85, to: 96), warp: null, softness: -3, ), @@ -156,6 +178,26 @@ void main() { if (i % 4 != 3) raw[i], ]; expect(pixels, orderedEquals(rgb)); + + w.settings.transparentBackground = true; + w.edit(); + expect(await w.generate(), isTrue, reason: w.error); + final transparent = w.inkPages.single!; + final copied = img.decodePng( + await compositeFinePage( + transparent, + w.fineAdjustments(transparent.fine!), + w.settings.inkLook, + ), + )!; + expect(copied.getPixel(0, 0).a, 0); + expect(await w.generate(preview: false), isTrue, reason: w.error); + final archive = ZipDecoder().decodeBytes(w.exportBytes!); + final exported = img.decodePng(archive.findFile('0.png')!.content)!; + expect( + exported.getBytes(order: img.ChannelOrder.rgba), + orderedEquals(copied.getBytes(order: img.ChannelOrder.rgba)), + ); }, skip: base.isEmpty ? 'Requires the local Rust engine' : false, ); diff --git a/app/test/workspace_test.dart b/app/test/workspace_test.dart index ef95a2de..8ad310e0 100644 --- a/app/test/workspace_test.dart +++ b/app/test/workspace_test.dart @@ -6,9 +6,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:handwriting_app/models/fine_edit.dart'; import 'package:handwriting_app/models/ink_page.dart'; import 'package:handwriting_app/services/api.dart'; +import 'package:handwriting_app/services/fine_draft.dart'; import 'package:handwriting_app/services/workspace.dart'; import 'package:handwriting_app/services/workspace_storage.dart'; import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; class MemoryStorage implements WorkspaceStorage { final values = {}; @@ -26,6 +28,23 @@ class MemoryStorage implements WorkspaceStorage { } } +class UnreliablePreferences extends Fake implements SharedPreferences { + final cache = {}, persisted = {}; + bool failExtension = false; + @override + String? get(String key) => cache[key]; + @override + String? getString(String key) => cache[key]; + + @override + Future setString(String key, String value) async { + cache[key] = value; + if (key == FineDraft.extensionSlot && failExtension) return false; + persisted[key] = value; + return true; + } +} + class ControlledApi extends HandwritingApi { ControlledApi({this.fineEdit = false}) : super('http://example.invalid'); final bool fineEdit; @@ -317,6 +336,78 @@ void main() { }, ); + test( + 'a failed rollback metadata write keeps the full draft and retries', + () async { + final current = '4' * 64, legacy = '3' * 64; + final prefs = UnreliablePreferences()..failExtension = true; + final storage = PreferencesWorkspaceStorage(prefs); + final w = Workspace(api: ControlledApi(), storage: storage); + await w.initialize(); + w.text = 'draft'; + final fine = FinePage( + current, + Uint8List(0), + const [], + rollbackKey: legacy, + ); + final page = InkPage(Uint8List(0), null, fine: fine); + w.generation + ..pages = [page.paper] + ..inkPages = [page] + ..previewRevision = w.editRevision; + final edit = FineEdits.fromJson({ + 'key': current, + 'glyphs': [ + { + 'id': 3, + 'dx': 4, + 'dy': 1, + 'scale': 110, + 'angle': 7, + 'opacity': 72, + 'opacity_ramp': [ + [10, 20], + [80, 90], + ], + }, + ], + }).glyphs[3]!; + w.applyFineEdits(fine, [edit]); + expect(await w.persistDraft(), isFalse); + expect(prefs.persisted[FineDraft.extensionSlot], isNull); + expect(storage.read(FineDraft.extensionSlot), isNotEmpty); + expect(await w.persistDraft(), isFalse); + final reopened = Workspace(api: ControlledApi(), storage: storage); + await reopened.initialize(); + expect(reopened.fineAdjustments(fine)[3], edit); + prefs.failExtension = false; + expect(await reopened.persistDraft(), isTrue); + final saved = jsonDecode(storage.read('flutter.workspace')!)['fineEdits']; + expect(saved['key'], legacy); + expect(saved['layoutKey'], current); + expect(storage.read(FineDraft.extensionSlot), isNotEmpty); + w.dispose(); + await w.persist(); + reopened.text = 'replacement'; + reopened.edit(); + prefs.failExtension = true; + expect(await reopened.persistDraft(), isFalse); + expect(storage.read(FineDraft.extensionSlot), isEmpty); + expect(prefs.persisted[FineDraft.extensionSlot], isNotEmpty); + expect(await reopened.persistDraft(), isFalse); + prefs.failExtension = false; + reopened.dispose(); + await reopened.persist(); + expect(prefs.persisted[FineDraft.extensionSlot], isEmpty); + expect(storage.read(FineDraft.extensionSlot), isEmpty); + expect( + jsonDecode(storage.read('flutter.workspace')!).containsKey('fineEdits'), + isFalse, + ); + }, + ); + test('dispose flushes last input before debounce fires', () async { final storage = MemoryStorage(); final w = Workspace(api: ControlledApi(), storage: storage); @@ -325,6 +416,7 @@ void main() { w.dispose(); await w.persist(); expect(jsonDecode(storage.values['flutter.workspace']!)['text'], '最后输入'); + expect(storage.values.containsKey(FineDraft.extensionSlot), isFalse); }); test( diff --git a/assets/examples/process-states-detail-31f9bf0ddada.webp b/assets/examples/process-states-detail-31f9bf0ddada.webp deleted file mode 100644 index 81dffc83..00000000 Binary files a/assets/examples/process-states-detail-31f9bf0ddada.webp and /dev/null differ diff --git a/assets/examples/process-states-detail-66221f736d96.webp b/assets/examples/process-states-detail-66221f736d96.webp new file mode 100644 index 00000000..253a510a Binary files /dev/null and b/assets/examples/process-states-detail-66221f736d96.webp differ diff --git a/assets/examples/rc-ladder-09c7d9dac754.webp b/assets/examples/rc-ladder-09c7d9dac754.webp deleted file mode 100644 index 32eeb6f6..00000000 Binary files a/assets/examples/rc-ladder-09c7d9dac754.webp and /dev/null differ diff --git a/assets/examples/rc-ladder-e6d4e4ec1974.webp b/assets/examples/rc-ladder-e6d4e4ec1974.webp new file mode 100644 index 00000000..94f2ec4c Binary files /dev/null and b/assets/examples/rc-ladder-e6d4e4ec1974.webp differ diff --git a/crates/handwriting-core/src/fine_edit.rs b/crates/handwriting-core/src/fine_edit.rs index 88934b08..674c6db7 100644 --- a/crates/handwriting-core/src/fine_edit.rs +++ b/crates/handwriting-core/src/fine_edit.rs @@ -1,7 +1,7 @@ //! 2026-11-18:按排版单元保存墨迹及页面坐标,供客户端实时编辑和导出。 use crate::{Cancellation, Error, LayoutStyle, Parameters, Result, export, ink_effects}; use base64::{Engine, engine::general_purpose::STANDARD}; -use image::{GrayImage, Rgba, RgbaImage}; +use image::{GrayImage, Pixel, Rgba, RgbaImage}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashMap; @@ -152,21 +152,53 @@ impl Adjustments { } } -// 旧偏移和当时的分页绑定;继续编辑同一稿时也不能换到新坐标系。 -pub(crate) fn uses_legacy_layout(text: &str, p: &Parameters) -> bool { - p.fine_edit - && p.fine_edits - .as_ref() - .is_some_and(|edits| edits.key == layout_key(text, p, b"panache-fine-2\0")) +// Crop extents set the pivot and gradient domain; keep them when reopening saved edits. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum LayoutVersion { + Fine2, + Fine3, + Coverage, +} + +impl LayoutVersion { + fn prefix(self) -> &'static [u8] { + match self { + Self::Fine2 => b"panache-fine-2\0", + Self::Fine3 => b"panache-fine-3\0", + Self::Coverage => b"panache-fine-4\0", + } + } + + pub(crate) fn for_document(text: &str, p: &Parameters) -> Self { + if p.fine_edit + && let Some(edits) = &p.fine_edits + { + for version in [Self::Fine3, Self::Fine2] { + if edits.key == layout_key(text, p, version.prefix()) { + return version; + } + } + } + Self::Coverage + } + + pub(crate) fn legacy_mask(self) -> bool { + self != Self::Coverage + } } pub(crate) fn document_key(text: &str, p: &Parameters) -> String { - let version: &[u8] = if uses_legacy_layout(text, p) { - b"panache-fine-2\0" - } else { - b"panache-fine-3\0" - }; - layout_key(text, p, version) + layout_key(text, p, LayoutVersion::for_document(text, p).prefix()) +} + +/// Older clients replay the common adjustment fields against their own tile bounds. +pub(crate) fn draft_keys(text: &str, p: &Parameters) -> (String, Option) { + let version = LayoutVersion::for_document(text, p); + ( + layout_key(text, p, version.prefix()), + (version == LayoutVersion::Coverage) + .then(|| layout_key(text, p, LayoutVersion::Fine3.prefix())), + ) } fn layout_key(text: &str, p: &Parameters, version: &[u8]) -> String { @@ -194,16 +226,27 @@ mod layout_version_tests { }; let current = document_key(text, ¶ms); let legacy = layout_key(text, ¶ms, b"panache-fine-2\0"); + let fine3 = layout_key(text, ¶ms, LayoutVersion::Fine3.prefix()); + assert_eq!( + draft_keys(text, ¶ms), + (current.clone(), Some(fine3.clone())) + ); + params.fine_edits = Some(Adjustments { + key: fine3.clone(), + glyphs: vec![], + }); + assert_eq!(draft_keys(text, ¶ms), (fine3, None)); assert_ne!(current, legacy); params.fine_edits = Some(Adjustments { key: legacy.clone(), glyphs: vec![], }); - assert!(uses_legacy_layout(text, ¶ms)); + assert!(LayoutVersion::for_document(text, ¶ms) == LayoutVersion::Fine2); assert_eq!(document_key(text, ¶ms), legacy); - assert!(!uses_legacy_layout("新内容", ¶ms)); + assert_eq!(draft_keys(text, ¶ms), (legacy, None)); + assert!(!LayoutVersion::for_document("新内容", ¶ms).legacy_mask()); params.fine_edits.as_mut().unwrap().key = current.clone(); - assert!(!uses_legacy_layout(text, ¶ms)); + assert!(!LayoutVersion::for_document(text, ¶ms).legacy_mask()); assert_eq!(document_key(text, ¶ms), current); } } @@ -228,6 +271,8 @@ pub(crate) const PAGE_TILE_BUDGET: usize = 32_000_000; #[derive(Debug, Serialize)] pub struct EncodedFinePage { pub key: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub rollback_key: Option, pub atlas: String, // 2026-11-18:每项为编号、纸面坐标、蒙版大小、图集坐标、基线。 pub glyphs: Vec<[i32; 8]>, @@ -236,7 +281,11 @@ pub struct EncodedFinePage { pub illustrations: std::collections::BTreeMap>, } -pub(crate) fn encode(key: &str, tiles: &[Tile], cancel: &Cancellation) -> Result { +pub(crate) fn encode( + keys: &(String, Option), + tiles: &[Tile], + cancel: &Cancellation, +) -> Result { let area: usize = tiles.iter().map(|t| t.mask.len()).sum(); let width = (area.isqrt() as u32).max(tiles.iter().map(|t| t.mask.width()).max().unwrap_or(1)); let (mut x, mut y, mut row) = (0, 0, 0); @@ -277,7 +326,8 @@ pub(crate) fn encode(key: &str, tiles: &[Tile], cancel: &Cancellation) -> Result } Ok(EncodedFinePage { illustrations, - key: key.to_owned(), + key: keys.0.clone(), + rollback_key: keys.1.clone(), atlas: STANDARD.encode(export::png(&atlas)?), glyphs, source_ranges: tiles.iter().map(|tile| tile.source).collect(), @@ -384,31 +434,65 @@ pub(crate) fn paint( 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.); - let mask = ink_effects::shape(tile.mask, thickness, softness, cancel)?; + let mut mask = ink_effects::shape(tile.mask, thickness, softness, cancel)?; let (w, h) = (f64::from(mask.width()), f64::from(mask.height())); let scale = edit.map_or(1., |v| f64::from(v.scale) / 100.); let angle = edit.map_or(0., |v| f64::from(v.angle) * std::f64::consts::PI / 180.); let (sin, cos) = angle.sin_cos(); - let cx = f64::from(tile.x + edit.map_or(0, |v| v.dx)) + w / 2.; - let cy = f64::from(tile.y + edit.map_or(0, |v| v.dy)) + h / 2.; + let x = tile.x + edit.map_or(0, |v| v.dx); + let y = tile.y + edit.map_or(0, |v| v.dy); + let cx = f64::from(x) + w / 2.; + let cy = f64::from(y) + h / 2.; let rx = scale * (cos.abs() * w + sin.abs() * h) / 2.; let ry = scale * (sin.abs() * w + cos.abs() * h) / 2.; let projected = edit .and_then(|v| v.warp) .and_then(|warp| projected_geometry(warp, w, h, scale, cos, sin)); - let [left, top, right, bottom] = projected.map_or([-rx, -ry, rx, ry], |p| p.0); + // A bilinear filter reaches half a pixel beyond each unfiltered edge. + let extra = scale * (sin.abs() + cos.abs()) / 2.; + let [left, top, right, bottom] = match (edit.and_then(|e| e.warp), projected) { + (Some(warp), Some((bounds, _))) => { + projected_geometry(warp, w + 1., h + 1., scale, cos, sin) + .map_or(bounds, |(padded, _)| padded) + } + _ => [-rx - extra, -ry - extra, rx + extra, ry + extra], + }; let color = edit .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; + let base_alpha = u32::from(base_opacity) * u32::from(base_fill[3]); + let ramp = edit.and_then(|edit| edit.opacity_ramp); + if base_alpha != 25_500 || opacity != 100 || ramp.is_some() { + for (y, row) in mask.rows_mut().enumerate() { + cancel.check()?; + let local = ramp.map_or(opacity, |ramp| { + let position = (y as f64 + 0.5) * 100. / h; (f64::from(opacity) * ramp.multiplier(position)).round() as u32 - }) - .collect::>() - }); + }); + for sample in row { + let alpha = (u32::from(sample[0]) * base_alpha + 12_750) / 25_500; + sample[0] = ((alpha * local + 50) / 100) as u8; + } + } + } + if projected.is_none() && scale == 1. && angle == 0. { + let width = paper.width() as usize; + for (dx, dy, row) in crate::render::clipped_rows(&mask, paper.dimensions(), x, y) { + cancel.check()?; + let start = (dy * width + dx) * 4; + let pixels = &mut paper.as_mut()[start..start + row.len() * 4]; + for (&alpha, pixel) in row.iter().zip(pixels.chunks_exact_mut(4)) { + if alpha != 0 { + ink_effects::blend_ink( + Rgba::from_slice_mut(pixel), + Rgba([color[0], color[1], color[2], alpha]), + ); + } + } + } + return Ok(()); + } for y in ((cy + top).floor().max(0.) as u32) ..((cy + bottom).ceil().max(0.) as u32).min(paper.height()) { @@ -424,29 +508,18 @@ pub(crate) fn paint( } else { (dx, dy) }; - let sx = ((dx * cos + dy * sin) / scale + w / 2. + 1e-9).floor(); - let sy = ((-dx * sin + dy * cos) / scale + h / 2. + 1e-9).floor(); - if !(sx >= 0. && sy >= 0. && sx < w && sy < h) { + // The mask stores samples at pixel centers. Projected corners describe pixel edges. + let sx = (dx * cos + dy * sin) / scale + w / 2.; + let sy = (-dx * sin + dy * cos) / scale + h / 2.; + if !(sx > -0.5 && sy > -0.5 && sx < w + 0.5 && sy < h + 0.5) { continue; } - let alpha = (u32::from(mask[(sx as u32, sy as u32)][0]) - * u32::from(base_opacity) - * u32::from(base_fill[3]) - + 12_750) - / 25_500; - 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; - pixel.blend(&Rgba([color[0], color[1], color[2], alpha as u8])); - continue; - } - for (ch, value) in pixel.0[..3].iter_mut().zip(color) { - *ch = - ((u32::from(*ch) * (255 - alpha) + u32::from(value) * alpha + 127) / 255) as u8; + let alpha = crate::render::sample_coverage(&mask, sx - 0.5, sy - 0.5); + if alpha != 0 { + ink_effects::blend_ink( + &mut paper[(x, y)], + Rgba([color[0], color[1], color[2], alpha]), + ); } } } @@ -457,6 +530,65 @@ pub(crate) fn paint( mod tests { use super::{Adjustment, Adjustments}; + #[test] + fn fine_paint_samples_pixel_centers_and_zero_edges_in_tinted_ramp_space() { + use super::*; + let tile = || Tile { + id: 1, + x: 4, + y: 4, + baseline: 6, + is_grid_table: false, + is_text: true, + is_native_diagram: false, + illustration: None, + source: None, + mask: GrayImage::from_raw(2, 2, vec![255, 127, 10, 200]).unwrap(), + }; + let mut paper = RgbaImage::new(10, 10); + let mut p = Parameters { + ink_thickness: 0., + ink_softness: 0., + ink_opacity: 100, + fill: [41, 106, 201, 255], + ..Parameters::default() + }; + paint(&mut paper, tile(), &p, None, &Cancellation::default()).unwrap(); + for (x, y, alpha) in [(4, 4, 255), (5, 4, 127), (4, 5, 10), (5, 5, 200)] { + assert_eq!(paper[(x, y)].0, [41, 106, 201, alpha]); + } + p.ink_opacity = 80; + p.fill[3] = 200; + let edit = Adjustment { + id: 1, + dx: 0, + dy: 0, + scale: 100, + angle: 0, + opacity: 80, + opacity_ramp: Some(OpacityRamp([[0, 0], [100, 100]])), + thickness: 0, + softness: 0, + color: None, + warp: Some([1., 0., 0.5, 0., 1., 0., 0., 0.]), + }; + let mut paper = RgbaImage::new(10, 10); + paint( + &mut paper, + tile(), + &p, + Some(&edit), + &Cancellation::default(), + ) + .unwrap(); + for (y, row) in [(4, [16, 24, 8]), (5, [2, 40, 38])] { + for (i, alpha) in row.into_iter().enumerate() { + assert_eq!(paper[(4 + i as u32, y)].0, [41, 106, 201, alpha]); + } + assert_eq!(paper[(7, y)].0, [0; 4]); + } + } + #[test] fn parses_perspective_edits_for_ten_thousand_glyphs() { let data = Adjustments { diff --git a/crates/handwriting-core/src/generation.rs b/crates/handwriting-core/src/generation.rs index 8e828ba7..49cfe926 100644 --- a/crates/handwriting-core/src/generation.rs +++ b/crates/handwriting-core/src/generation.rs @@ -63,10 +63,10 @@ pub fn generate( })?; } Output::InkLayers(emit) => { - let key = request + let keys = request .params .fine_edit - .then(|| fine_edit::document_key(&request.text, &request.params)); + .then(|| fine_edit::draft_keys(&request.text, &request.params)); crate::render::render_pages(request, cancel, usize::MAX, |index, paper, alpha| { let alpha = alpha.ok_or_else(|| Error::new("invalid_parameter", "ink_layers"))?; cancel.check()?; @@ -83,7 +83,7 @@ pub fn generate( PageInk::Fine(tiles) => ( None, Some(fine_edit::encode( - key.as_deref().unwrap_or_default(), + keys.as_ref().expect("fine pages require fine edit mode"), &tiles, cancel, )?), diff --git a/crates/handwriting-core/src/ink_effects.rs b/crates/handwriting-core/src/ink_effects.rs index 681053de..346d8ec9 100644 --- a/crates/handwriting-core/src/ink_effects.rs +++ b/crates/handwriting-core/src/ink_effects.rs @@ -3,10 +3,11 @@ use image::{GrayImage, Luma, Rgba, RgbaImage}; use crate::{Cancellation, Parameters, Result}; pub fn coverage(ink: &RgbaImage) -> GrayImage { - GrayImage::from_fn(ink.width(), ink.height(), |x, y| { - let pixel = ink[(x, y)]; - Luma([((u16::from(255 - pixel[0]) * u16::from(pixel[3]) + 127) / 255) as u8]) - }) + let samples = ink + .pixels() + .map(|pixel| ((u16::from(255 - pixel[0]) * u16::from(pixel[3]) + 127) / 255) as u8) + .collect(); + GrayImage::from_raw(ink.width(), ink.height(), samples).unwrap() } pub fn transparent_mask(alpha: &GrayImage) -> RgbaImage { @@ -15,6 +16,33 @@ pub fn transparent_mask(alpha: &GrayImage) -> RgbaImage { }) } +/// Source-over on straight RGBA. Transparent paper keeps the exact pen RGB, +/// including on edges with only one level of coverage. +#[inline] +pub(crate) fn blend_ink(pixel: &mut Rgba, ink: Rgba) { + if ink[3] == 0 { + return; + } + if ink[3] == 255 || pixel[3] == 0 { + *pixel = ink; + return; + } + let alpha = u32::from(ink[3]); + if pixel[3] == 255 { + for (ch, value) in pixel.0[..3].iter_mut().zip(ink.0) { + *ch = ((u32::from(*ch) * (255 - alpha) + u32::from(value) * alpha + 127) / 255) as u8; + } + return; + } + let dest = u32::from(pixel[3]) * (255 - alpha); + let source = alpha * 255; + let total = source + dest; + for (ch, value) in pixel.0[..3].iter_mut().zip(ink.0) { + *ch = ((u32::from(*ch) * dest + u32::from(value) * source + total / 2) / total) as u8; + } + pixel[3] = ((total + 127) / 255) as u8; +} + enum Kernel { Max, Min, @@ -132,16 +160,10 @@ pub fn composite( (u32::from(mask[(x, y)][0]) * u32::from(p.ink_opacity) * u32::from(p.fill[3]) + 12_750) / 25_500; - let pixel = &mut paper[(x, y)]; - if pixel[3] < 255 { - use image::Pixel; - pixel.blend(&Rgba([p.fill[0], p.fill[1], p.fill[2], alpha as u8])); - continue; - } - for (channel, ink) in pixel.0[..3].iter_mut().zip(p.fill) { - *channel = ((u32::from(*channel) * (255 - alpha) + u32::from(ink) * alpha + 127) - / 255) as u8; - } + blend_ink( + &mut paper[(x, y)], + Rgba([p.fill[0], p.fill[1], p.fill[2], alpha as u8]), + ); } } Ok(paper) diff --git a/crates/handwriting-core/src/render.rs b/crates/handwriting-core/src/render.rs index c3d93bca..f9da9b5c 100644 --- a/crates/handwriting-core/src/render.rs +++ b/crates/handwriting-core/src/render.rs @@ -39,6 +39,7 @@ mod glyph; mod homework; mod illustration; mod ink; +pub(crate) use ink::coverage::{clipped_rows, sample_coverage}; mod line; mod paragraph; mod units; @@ -68,7 +69,8 @@ struct Pages<'a, F> where F: FnMut(usize, RgbaImage, Option) -> Result<()>, { - background: RgbaImage, + // Transparent pages can start with a zeroed canvas of the same size. + background: Option, canvas: RgbaImage, ink_layer: Option, mask: GrayImage, @@ -80,7 +82,7 @@ where x: f32, y: f32, previous_bottom: f32, - table_clearance: bool, + fine_layout: fine_edit::LayoutVersion, table_edge: Vec, written_lines: usize, line: Vec, @@ -113,8 +115,9 @@ impl) -> Result<()>> Pages<'_, F> { ) } - fn emit_page(&mut self, force: bool) -> Result<()> { - if (!self.dirty && !force) || self.stopped { + fn emit_page(&mut self, end_of_document: bool) -> Result<()> { + let empty_document = end_of_document && self.count == 0; + if (!self.dirty && !empty_document) || self.stopped { return Ok(()); } self.cancel.check()?; @@ -122,7 +125,8 @@ impl) -> Result<()>> Pages<'_, F> { return Err(Error::new("page_limit", "页数超出限制")); } self.flush_ink()?; - let canvas = std::mem::replace(&mut self.canvas, self.background.clone()); + let canvas = std::mem::take(&mut self.canvas); + let (width, height) = canvas.dimensions(); let alpha = if self.p.fine_edit { self.tile_area = 0; Some(PageInk::Fine(std::mem::take(&mut self.tiles))) @@ -135,8 +139,15 @@ impl) -> Result<()>> Pages<'_, F> { }; (self.emit)(self.count, canvas, alpha)?; self.count += 1; - self.stopped = self.count >= self.stop_after + self.stopped = end_of_document + || self.count >= self.stop_after || (self.p.preview && !self.p.full_preview && !self.p.pdf_save); + if !self.stopped { + self.canvas = self + .background + .clone() + .unwrap_or_else(|| RgbaImage::new(width, height)); + } self.x = self.p.left_margin; self.y = self.p.top_margin + self.p.line_spacing; self.previous_bottom = self.p.top_margin; @@ -149,9 +160,20 @@ impl) -> Result<()>> Pages<'_, F> { return Ok(()); } let mut units = std::mem::take(&mut self.line); - let mut layout = line::LineLayout::fit(&mut units, self.p, self.canvas.height()); + let mut layout = line::LineLayout::fit( + &mut units, + self.p, + self.canvas.height(), + self.fine_layout.legacy_mask(), + ); let mut anchor = layout.baseline(self.y, self.dirty.then_some(self.previous_bottom)); - if !self.table_edge.is_empty() && line::intrudes_on_table(&units, anchor, &self.table_edge) + if !self.table_edge.is_empty() + && line::intrudes_on_table( + &units, + anchor, + &self.table_edge, + self.fine_layout.legacy_mask(), + ) { let bottom = self.table_edge.iter().copied().max().unwrap_or_default(); anchor = layout.baseline(anchor, Some(bottom as f32)); @@ -172,14 +194,28 @@ impl) -> Result<()>> Pages<'_, F> { u.x + u.glyph.left, anchor.round() as i32 + u.dy + u.glyph.top, ); - if self.table_clearance && u.is_grid_table { + if self.fine_layout != fine_edit::LayoutVersion::Fine2 && u.is_grid_table { self.table_edge.resize(self.canvas.width() as usize, 0); } if self.p.fine_edit { - for tile in fine::capture(u, origin, anchor.round() as i32, self.p, self.cancel)? { + for tile in fine::capture( + u, + origin, + anchor.round() as i32, + self.p, + self.fine_layout.legacy_mask(), + self.cancel, + )? { if tile.is_grid_table { - for (x, y, _) in - tile.mask.enumerate_pixels().filter(|(_, _, p)| p[0] >= 128) + let minimum = if self.fine_layout.legacy_mask() { + 128 + } else { + 1 + }; + for (x, y, _) in tile + .mask + .enumerate_pixels() + .filter(|(_, _, p)| p[0] >= minimum) { if let Some(edge) = self.table_edge.get_mut((tile.x + x as i32) as usize) @@ -197,6 +233,7 @@ impl) -> Result<()>> Pages<'_, F> { ink::RigidPlacement { origin, align_to_rulings: u.align_to_rulings, + protect_lines: u.is_native_diagram, table_edge: if u.is_grid_table { &mut self.table_edge } else { @@ -218,9 +255,9 @@ impl) -> Result<()>> Pages<'_, F> { self.dirty = true; Ok(()) } - fn flush(&mut self, force: bool) -> Result<()> { + fn flush(&mut self, end_of_document: bool) -> Result<()> { self.finish_line()?; - self.emit_page(force) + self.emit_page(end_of_document) } fn newline(&mut self) -> Result<()> { if self.line.is_empty() { @@ -423,10 +460,16 @@ fn render_planes( }; let mut composer = composition::UnitComposer::new(p, &r.text, source.as_deref(), (w, h)); let mut glyphs = Glyphs::with_parameters(&r.fonts, p)?; + let fine_layout = fine_edit::LayoutVersion::for_document(&r.text, &r.params); + glyphs.use_legacy_masks(fine_layout.legacy_mask()); let mut pages = Pages { - canvas: background.clone(), + canvas: if transparent { + std::mem::take(&mut background) + } else { + background.clone() + }, ink_layer: (p.ink_layers && !p.fine_edit).then(|| RgbaImage::new(w, h)), - background, + background: (!transparent).then_some(background), mask: if p.fine_edit { GrayImage::new(0, 0) } else { @@ -440,7 +483,7 @@ fn render_planes( x: p.left_margin, y: p.top_margin + p.line_spacing, previous_bottom: p.top_margin, - table_clearance: !fine_edit::uses_legacy_layout(&r.text, &r.params), + fine_layout, table_edge: Vec::new(), written_lines: 0, line: Vec::new(), @@ -474,7 +517,7 @@ fn render_planes( for (offset, unit) in rest.enumerate() { let mut g = glyphs.unit(unit, p.font_size, i + 1 + offset)?; if let Some(cell) = fixed_cell(unit, p) { - g = g.place_in_cell(cell); + g = g.place_in_cell(cell, fine_layout.legacy_mask()); } width = width.max(cursor + g.right() as f32); cursor += g.step( @@ -575,9 +618,13 @@ fn render_planes( } let usable_height = h as f32 - p.top_margin - p.bottom_margin; let cell = fixed_cell(unit, p); - let mut g = glyph.fit(paragraph.usable_width(), usable_height); + let mut g = glyph.fit( + paragraph.usable_width(), + usable_height, + fine_layout.legacy_mask(), + ); if let Some(cell) = cell { - g = g.place_in_cell(cell); + g = g.place_in_cell(cell, fine_layout.legacy_mask()); } let jitter_x = if cell.is_none() && p.grid_layout && keeps_grid_cell(unit) { normal(&mut pages.rng, p.word_spacing_sigma) @@ -619,7 +666,7 @@ fn render_planes( } } if !pages.stopped { - pages.flush(pages.count == 0)?; + pages.flush(true)?; } Ok(pages.count) } @@ -662,15 +709,15 @@ mod ruled_tests { line_spacing: 45., ..Default::default() }; - let layout = line::LineLayout::fit(&mut units, ¶ms, 110); + let layout = line::LineLayout::fit(&mut units, ¶ms, 110, false); let baseline = 96.; let mut edge = vec![0; 180]; edge[60..90].fill(102); edge[10..18].fill(68); - assert!(!line::intrudes_on_table(&units, baseline, &edge)); + assert!(!line::intrudes_on_table(&units, baseline, &edge, false)); assert!(!layout.overflows(baseline)); edge[10..18].fill(89); - assert!(line::intrudes_on_table(&units, baseline, &edge)); + assert!(line::intrudes_on_table(&units, baseline, &edge, false)); assert!(layout.overflows(layout.baseline(baseline, Some(102.)))); } @@ -701,7 +748,7 @@ mod ruled_tests { let cancel = Cancellation::default(); let bg = blank_paper(180, 193, &p); let mut pages = Pages { - background: bg.clone(), + background: Some(bg.clone()), canvas: bg, ink_layer: None, mask: GrayImage::new(180, 193), @@ -713,7 +760,7 @@ mod ruled_tests { x: 10., y: 10. + spacing, previous_bottom: 10., - table_clearance: true, + fine_layout: fine_edit::LayoutVersion::Coverage, table_edge: Vec::new(), written_lines: 0, line: vec![], diff --git a/crates/handwriting-core/src/render/composition.rs b/crates/handwriting-core/src/render/composition.rs index b9ee6c71..f5d48a10 100644 --- a/crates/handwriting-core/src/render/composition.rs +++ b/crates/handwriting-core/src/render/composition.rs @@ -65,7 +65,7 @@ impl<'a> UnitComposer<'a> { { let wrong = glyphs.glyph(c, size)?; return Ok(PreparedGlyph { - glyph: cross_out(wrong, glyph, p, self.page_size, rng)?, + glyph: cross_out(wrong, glyph, p, self.page_size, rng, glyphs.legacy_mask())?, compound: true, fine_parts: None, }); @@ -101,6 +101,7 @@ fn cross_out( p: &Parameters, (w, h): (u32, u32), rng: &mut ChaCha8Rng, + legacy: bool, ) -> Result { let length = (p.font_size * 2f32.sqrt() + normal(rng, p.strikethrough_length_sigma)) .clamp(0., (w as f32 + h as f32).min(16384.)); @@ -121,9 +122,10 @@ fn cross_out( .max(wrong.right() as f32) .max(stroke_right as f32) .round() as i32; - Glyphs::compose( + Glyphs::compose_paths( correct.advance + shift as f32, vec![(wrong, 0, 0), (correct, shift, 0)], vec![(path, width)], + legacy, ) } diff --git a/crates/handwriting-core/src/render/fine.rs b/crates/handwriting-core/src/render/fine.rs index b5eadf85..5699a313 100644 --- a/crates/handwriting-core/src/render/fine.rs +++ b/crates/handwriting-core/src/render/fine.rs @@ -32,10 +32,11 @@ pub(super) fn capture( origin: (i32, i32), baseline: i32, p: &Parameters, + legacy_mask: bool, cancel: &Cancellation, ) -> Result> { let Some(parts) = unit.fine_parts else { - return Ok(capture_one(unit, origin, baseline, p, cancel)? + return Ok(capture_one(unit, origin, baseline, p, legacy_mask, cancel)? .into_iter() .collect()); }; @@ -52,15 +53,7 @@ pub(super) fn capture( let (w, h) = glyph.mask.dimensions(); let w = (u64::from(w) * u64::from(width) / u64::from(old_width)).max(1) as u32; let h = (u64::from(h) * u64::from(height) / u64::from(old_height)).max(1) as u32; - let mut mask = GrayImage::new(w, h); - for (old_x, old_y, pixel) in glyph.mask.enumerate_pixels() { - let at = ( - old_x * w / glyph.mask.width(), - old_y * h / glyph.mask.height(), - ); - mask[at][0] = mask[at][0].max(pixel[0]); - } - glyph.mask = mask; + glyph.resize_mask(w, h, legacy_mask); } let child = LineUnit { glyph, @@ -74,6 +67,7 @@ pub(super) fn capture( (origin.0 + x as i32, origin.1 + y as i32), baseline, p, + legacy_mask, cancel, )? { tiles.push(tile); @@ -118,6 +112,7 @@ fn capture_one( origin: (i32, i32), baseline: i32, p: &Parameters, + legacy_mask: bool, cancel: &Cancellation, ) -> Result> { if !unit.glyph.ink { @@ -147,12 +142,18 @@ fn capture_one( ink_depth_sigma: p.ink_depth_sigma, ..Parameters::default() }; - ink::paint_math_unit( + let paint = if legacy_mask { + ink::legacy_paint_math_unit + } else { + ink::paint_math_unit + }; + paint( &mut rendered, &raw, ink::RigidPlacement { origin: (radius as i32, radius as i32), align_to_rulings: unit.align_to_rulings, + protect_lines: unit.is_native_diagram, table_edge: &mut [], }, &tile_params, @@ -165,20 +166,38 @@ fn capture_one( ink::paste_mask(&mut padded, &raw, radius as i32, radius as i32); raw = padded; } - ink::perturb(&mut raw, &mut rendered, p, &mut rng, cancel)?; + let perturb = if legacy_mask { + ink::legacy_perturb + } else { + ink::perturb + }; + perturb(&mut raw, &mut rendered, p, &mut rng, cancel)?; } let raw = ink_effects::coverage(&rendered); + if raw.is_empty() { + return Ok(None); + } let (mut left, mut top, mut right, mut bottom) = (raw.width(), raw.height(), 0, 0); - for (x, y, _) in raw.enumerate_pixels().filter(|(_, _, v)| v[0] != 0) { - (left, top, right, bottom) = (left.min(x), top.min(y), right.max(x + 1), bottom.max(y + 1)); + for (y, row) in raw.as_raw().chunks_exact(raw.width() as usize).enumerate() { + if let Some(first) = row.iter().position(|&sample| sample != 0) { + left = left.min(first as u32); + right = right.max(row.iter().rposition(|&sample| sample != 0).unwrap() as u32 + 1); + top = top.min(y as u32); + bottom = y as u32 + 1; + } } if right == 0 { return Ok(None); } let pad = fine_edit::PAD; - let crop = image::imageops::crop_imm(&raw, left, top, right - left, bottom - top).to_image(); - let mut mask = GrayImage::new(crop.width() + pad * 2, crop.height() + pad * 2); - ink::paste_mask(&mut mask, &crop, pad as i32, pad as i32); + let mut mask = GrayImage::new(right - left + pad * 2, bottom - top + pad * 2); + let stride = mask.width() as usize; + for (y, row) in (top..bottom).zip(mask.as_mut().chunks_exact_mut(stride).skip(pad as usize)) { + let start = y as usize * raw.width() as usize + left as usize; + let width = (right - left) as usize; + row[pad as usize..pad as usize + width] + .copy_from_slice(&raw.as_raw()[start..start + width]); + } Ok(Some(fine_edit::Tile { is_grid_table: unit.is_grid_table, is_text: unit.is_text, diff --git a/crates/handwriting-core/src/render/glyph.rs b/crates/handwriting-core/src/render/glyph.rs index b0f257a1..149ad059 100644 --- a/crates/handwriting-core/src/render/glyph.rs +++ b/crates/handwriting-core/src/render/glyph.rs @@ -6,6 +6,7 @@ use std::collections::HashMap; mod circled; mod pen; mod radical; +mod stroke; pub(super) fn is_circled(c: char) -> bool { circled::number(c).is_some() } @@ -59,18 +60,18 @@ impl Glyph { } } } - pub(super) fn place_in_cell(self, cell: f32) -> Self { - let mut glyph = self.fit(cell, f32::INFINITY); + pub(super) fn place_in_cell(self, cell: f32, legacy: bool) -> Self { + let mut glyph = self.fit(cell, f32::INFINITY, legacy); glyph.left = ((cell - glyph.mask.width() as f32) / 2.).round().max(0.) as i32; glyph.advance = cell; glyph } - pub fn fit(mut self, width: f32, height: f32) -> Self { - self.fit_in_place(width, height); + pub fn fit(mut self, width: f32, height: f32, legacy: bool) -> Self { + self.fit_in_place(width, height, legacy); self } - pub(super) fn fit_in_place(&mut self, width: f32, height: f32) { + pub(super) fn fit_in_place(&mut self, width: f32, height: f32, legacy: bool) { let footprint = self.advance.max(self.right() as f32) - self.left.min(0) as f32; let ratio = (width / footprint.max(1.)) .min(height / self.mask.height() as f32) @@ -78,17 +79,24 @@ impl Glyph { if ratio < 1. { let width = (self.mask.width() as f32 * ratio).floor().max(1.) as u32; let height = (self.mask.height() as f32 * ratio).floor().max(1.) as u32; + self.resize_mask(width, height, legacy); + self.left = (self.left as f32 * ratio).floor() as i32; + self.top = (self.top as f32 * ratio).floor() as i32; + self.advance = (self.advance * ratio).floor().max(1.); + } + } + + pub(super) fn resize_mask(&mut self, width: u32, height: u32, legacy: bool) { + if legacy { let mut resized = GrayImage::new(width, height); - // 2026-10-15:缩小时保留每一条墨迹,不能把单像素根顶/分数线平均成阈值以下而整式消失。 for (x, y, p) in self.mask.enumerate_pixels() { - let xx = (u64::from(x) * u64::from(width) / u64::from(self.mask.width())) as u32; - let yy = (u64::from(y) * u64::from(height) / u64::from(self.mask.height())) as u32; + let xx = x * width / self.mask.width(); + let yy = y * height / self.mask.height(); resized[(xx, yy)][0] = resized[(xx, yy)][0].max(p[0]); } self.mask = resized; - self.left = (self.left as f32 * ratio).floor() as i32; - self.top = (self.top as f32 * ratio).floor() as i32; - self.advance = (self.advance * ratio).floor().max(1.); + } else { + self.mask = stroke::resize_coverage(&self.mask, width, height); } } } @@ -117,6 +125,12 @@ impl<'a> Glyphs<'a> { drawing_stream: 0, } } + pub(super) fn legacy_mask(&self) -> bool { + self.pen.legacy_mask + } + pub(super) fn use_legacy_masks(&mut self, legacy: bool) { + self.pen.legacy_mask = legacy; + } pub fn with_parameters(book: &'a FontBook, p: &Parameters) -> Result { let mut glyphs = Self::new(book); glyphs.latin_font = p @@ -217,6 +231,15 @@ impl<'a> Glyphs<'a> { advance: f32, children: Vec, paths: Vec, + ) -> Result { + Self::compose_paths(advance, children, paths, false) + } + + pub(super) fn compose_paths( + advance: f32, + children: Vec, + paths: Vec, + legacy: bool, ) -> Result { let mut bounds: Option<(i32, i32, i32, i32)> = None; let mut include = |b: (i32, i32, i32, i32)| { @@ -246,12 +269,13 @@ impl<'a> Glyphs<'a> { } for (points, thickness) in paths { for pair in points.windows(2) { - Self::stroke( - &mut mask, - (pair[0].0 - left, pair[0].1 - top), - (pair[1].0 - left, pair[1].1 - top), - thickness, - ); + let a = (pair[0].0 - left, pair[0].1 - top); + let b = (pair[1].0 - left, pair[1].1 - top); + if legacy { + Self::legacy_stroke(&mut mask, a, b, thickness); + } else { + stroke::draw(&mut mask, a, b, thickness as f32, 0., false); + } } } Ok(Self::trim(Glyph { @@ -263,7 +287,7 @@ impl<'a> Glyphs<'a> { })) } // 2026-10-15:对角线使用四连通笔画,根钩和顶线在连通域扰动后仍保持连笔。 - fn stroke(mask: &mut GrayImage, a: (i32, i32), b: (i32, i32), thickness: i32) { + fn legacy_stroke(mask: &mut GrayImage, a: (i32, i32), b: (i32, i32), thickness: i32) { let steps = (b.0 - a.0).abs().max((b.1 - a.1).abs()).max(1); let radius = thickness / 2; let mut previous = a; @@ -459,7 +483,12 @@ impl<'a> Glyphs<'a> { } _ => paths.push((vec![(left, y), (right, y)], thickness)), } - Self::compose(body.advance, vec![(body, 0, 0)], paths) + Self::compose_paths( + body.advance, + vec![(body, 0, 0)], + paths, + self.pen.legacy_mask, + ) } _ => Ok(Glyph::empty(0.)), } diff --git a/crates/handwriting-core/src/render/glyph/circled.rs b/crates/handwriting-core/src/render/glyph/circled.rs index 1ea8b8e9..98e8ed2e 100644 --- a/crates/handwriting-core/src/render/glyph/circled.rs +++ b/crates/handwriting-core/src/render/glyph/circled.rs @@ -89,9 +89,11 @@ impl Glyphs<'_> { let center = (width / 2., (reference.top + reference.bottom()) as f32 / 2.); let inner_size = size * if value < 10 { 0.64 } else { 0.52 }; let nodes: Vec<_> = value.to_string().chars().map(Node::Char).collect(); - let digits = self - .sequence(&nodes, inner_size.max(32.))? - .fit(width * 0.52, height * 0.55); + let digits = self.sequence(&nodes, inner_size.max(32.))?.fit( + width * 0.52, + height * 0.55, + self.pen.legacy_mask, + ); let x = (center.0 - digits.mask.width() as f32 / 2.).round() as i32 - digits.left; let y = (center.1 - digits.mask.height() as f32 / 2.).round() as i32 - digits.top; let phase = value as f32 * 0.71 + (self.pen.seed % 13) as f32 * 0.17; diff --git a/crates/handwriting-core/src/render/glyph/circuit.rs b/crates/handwriting-core/src/render/glyph/circuit.rs index b45ed03e..42e333d8 100644 --- a/crates/handwriting-core/src/render/glyph/circuit.rs +++ b/crates/handwriting-core/src/render/glyph/circuit.rs @@ -237,28 +237,10 @@ fn pen_paths(paths: Vec, width: f32, pen_offset: f32) -> Result { let y = y - (g.top + g.bottom()) / 2; children.push((g, x, y)); } - // 刚性墨迹以 128 为阈值,偶数像素笔宽须落在两列/两行之间。 + // 偶数笔宽的流程图居于相邻像素之间,保持横竖边框对齐。 let offset = if circuit.flowchart && (width.round() as u32).is_multiple_of(2) { 0.5 } else { @@ -465,7 +447,7 @@ mod tests { } #[test] - fn subpixel_wires_survive_the_page_ink_threshold() { + fn subpixel_wires_remain_continuous_in_all_directions() { 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, 0.) diff --git a/crates/handwriting-core/src/render/glyph/pen.rs b/crates/handwriting-core/src/render/glyph/pen.rs index 6c822433..73dd070d 100644 --- a/crates/handwriting-core/src/render/glyph/pen.rs +++ b/crates/handwriting-core/src/render/glyph/pen.rs @@ -15,6 +15,7 @@ pub(super) struct MathPen { pub(super) root: super::radical::RootShape, pub naturalness: f32, pub seed: u64, + pub(super) legacy_mask: bool, } impl MathPen { @@ -27,10 +28,13 @@ impl MathPen { }; let width = (source.width() as f32 * size / 96.).round().max(3.) as u32; let height = (source.height() as f32 * size / 96.).round().max(3.) as u32; - let mut mask = - image::imageops::resize(source, width, height, image::imageops::FilterType::Triangle); - // 2026-10-24:缩小字体原笔画时保留墨迹,不能把草写尖角平均成断续小点。 - if size < 96. { + let mut mask = if size < 96. && !self.legacy_mask { + super::stroke::resize_coverage(source, width, height) + } else { + image::imageops::resize(source, width, height, image::imageops::FilterType::Triangle) + }; + // Recreate the original chevron width and tile bounds in saved layouts. + if size < 96. && self.legacy_mask { for (x, y, p) in source.enumerate_pixels() { let xx = x * width / source.width(); let yy = y * height / source.height(); @@ -231,7 +235,7 @@ impl MathPen { .collect() }) .collect(); - let high = Glyphs::compose(advance * scale as f32, vec![], dense)?; + let high = Glyphs::compose_paths(advance * scale as f32, vec![], dense, self.legacy_mask)?; let left = (high.left as f32 / scale as f32).floor() as i32; let top = (high.top as f32 / scale as f32).floor() as i32; let right = (high.right() as f32 / scale as f32).ceil() as i32; diff --git a/crates/handwriting-core/src/render/glyph/pen/sample.rs b/crates/handwriting-core/src/render/glyph/pen/sample.rs index b353a646..0f3af7ac 100644 --- a/crates/handwriting-core/src/render/glyph/pen/sample.rs +++ b/crates/handwriting-core/src/render/glyph/pen/sample.rs @@ -35,6 +35,7 @@ impl MathPen { root: RootShape::sample(font), naturalness: 0., seed: 0, + legacy_mask: false, } } } diff --git a/crates/handwriting-core/src/render/glyph/stroke.rs b/crates/handwriting-core/src/render/glyph/stroke.rs new file mode 100644 index 00000000..846ce4bc --- /dev/null +++ b/crates/handwriting-core/src/render/glyph/stroke.rs @@ -0,0 +1,118 @@ +use image::{GrayImage, Luma}; + +/// Integrate coverage over each destination pixel. Integer coordinates use units +/// of 1/destination_size on each source axis, so shared edges agree exactly. +pub(super) fn resize_coverage(source: &GrayImage, width: u32, height: u32) -> GrayImage { + let (sw, sh) = source.dimensions(); + let area = u64::from(sw) * u64::from(sh); + let mut result = GrayImage::from_fn(width, height, |x, y| { + let (left, right) = (x * sw, (x + 1) * sw); + let (top, bottom) = (y * sh, (y + 1) * sh); + let mut sum = 0u64; + for sy in top / height..bottom.div_ceil(height) { + let dy = bottom.min((sy + 1) * height) - top.max(sy * height); + for sx in left / width..right.div_ceil(width) { + let dx = right.min((sx + 1) * width) - left.max(sx * width); + sum += u64::from(source[(sx, sy)][0]) * u64::from(dx) * u64::from(dy); + } + } + // Even an isolated fine stroke retains one coverage level at extreme reductions. + Luma([((sum + area / 2) / area).max(u64::from(sum > 0)) as u8]) + }); + // Optical minimum for compressed strokes: keep a projected center at half + // opacity. Other samples retain their measured coverage, including fringes. + if width < sw || height < sh { + for (x, y, _) in source.enumerate_pixels().filter(|(_, _, p)| p[0] >= 128) { + let xx = (2 * x + 1) * width / (2 * sw); + let yy = (2 * y + 1) * height / (2 * sh); + let center = &mut result[(xx, yy)][0]; + *center = (*center).max(128); + } + } + result +} + +/// Coverage of a round-ended pen, sampled within a narrow band along its major axis. +pub(super) fn draw( + mask: &mut GrayImage, + a: (i32, i32), + b: (i32, i32), + diameter: f32, + offset: f32, + thin_wire: bool, +) { + let steep = (b.1 - a.1).abs() > (b.0 - a.0).abs(); + let axes = |(x, y)| if steep { (y, x) } else { (x, y) }; + let (ax, ay) = axes(a); + let (bx, by) = axes(b); + let (dx, dy) = ((bx - ax) as f32, (by - ay) as f32); + let length_sq = (dx * dx + dy * dy).max(1.); + let reach = (diameter + 1.) * 0.5; + let slope = if dx == 0. { 0. } else { dy / dx }; + let band = reach * (1. + slope * slope).sqrt(); + let (w, h) = axes((mask.width() as i32, mask.height() as i32)); + let first = (ax.min(bx) as f32 + offset - reach).ceil() as i32; + let last = (ax.max(bx) as f32 + offset + reach).floor() as i32; + for x in first.max(0)..=last.min(w - 1) { + let px = (x - ax) as f32 - offset; + let center = ay as f32 + offset + (px * slope).clamp(0f32.min(dy), 0f32.max(dy)); + let low = ((center - band).floor() as i32).max(0); + let high = ((center + band).ceil() as i32).min(h - 1); + for y in low..=high { + let py = (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 = ((reach - distance).clamp(0., diameter.min(1.)) * 255.).round() as u8; + let alpha = if thin_wire && diameter < 1. && distance <= 0.5 { + alpha.max(128) + } else { + alpha + }; + let (mx, my) = axes((x, y)); + let dest = &mut mask[(mx as u32, my as u32)][0]; + *dest = (*dest).max(alpha); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reduction_integrates_fractional_pixel_footprints_and_protects_thin_rules() { + let ramp = GrayImage::from_raw(3, 1, vec![15, 75, 105]).unwrap(); + assert_eq!(resize_coverage(&ramp, 2, 1).as_raw(), &[35, 95]); + + let grid = GrayImage::from_fn(24, 24, |x, y| { + Luma([if x == 6 || y == 10 { 255 } else { 0 }]) + }); + let reduced = resize_coverage(&grid, 6, 6); + for (x, y, p) in reduced.enumerate_pixels() { + if x == 1 || y == 2 { + assert!( + (128..255).contains(&p[0]), + "missing or oversaturated rule at {x}, {y}" + ); + } else { + assert_eq!(p[0], 0); + } + } + } + + #[test] + fn round_pen_weights_even_rules_and_diagonals_without_broadening_them() { + let mut rule = GrayImage::new(30, 15); + draw(&mut rule, (2, 7), (27, 7), 2., 0., false); + assert_eq!( + [rule[(10, 6)][0], rule[(10, 7)][0], rule[(10, 8)][0]], + [128, 255, 128] + ); + let mut slope = GrayImage::new(30, 15); + draw(&mut slope, (2, 2), (27, 12), 1., 0., false); + assert!(slope.pixels().any(|p| (1..128).contains(&p[0]))); + for x in 2..=27 { + assert!((0..15).any(|y| slope[(x, y)][0] >= 128)); + } + } +} diff --git a/crates/handwriting-core/src/render/glyph/table.rs b/crates/handwriting-core/src/render/glyph/table.rs index 094e637b..f9c5ebb0 100644 --- a/crates/handwriting-core/src/render/glyph/table.rs +++ b/crates/handwriting-core/src/render/glyph/table.rs @@ -175,8 +175,12 @@ impl Glyphs<'_> { inset }; let advance = (width + inset + right + cells.pad) as f32; - let mut result = - Self::compose(advance, cells.positioned(table.kind, inset, offset), paths)?; + let mut result = Self::compose_paths( + advance, + cells.positioned(table.kind, inset, offset), + paths, + self.pen.legacy_mask, + )?; if table.kind == TableKind::Matrix { let axis = self.glyph('x', size)?; result.top += (axis.top + axis.bottom() - result.top - result.bottom()) / 2; diff --git a/crates/handwriting-core/src/render/glyph/tests.rs b/crates/handwriting-core/src/render/glyph/tests.rs index 6b0cc04d..5cb63899 100644 --- a/crates/handwriting-core/src/render/glyph/tests.rs +++ b/crates/handwriting-core/src/render/glyph/tests.rs @@ -188,7 +188,7 @@ fn distribution_table_has_two_dimensional_handwritten_ink_and_continuous_rules() "outer vertical grid rule" ); } - let fit = g.clone().fit(120., 100.); + let fit = g.clone().fit(120., 100., false); assert!(fit.mask.width() <= 120 && fit.mask.height() <= 100); assert!(fit.ink); } @@ -373,7 +373,7 @@ fn matrix_delimiters_are_continuous_equal_weight_and_do_not_add_a_grid() { .sequence(&text::parse("⟦ cases: (1)/(2) x≥0 ; -x² x<0 ⟧"), size) .unwrap(); assert!(cases.ink); - let fitted = cases.fit(100., 90.); + let fitted = cases.fit(100., 90., false); assert!(fitted.mask.width() <= 100 && fitted.mask.height() <= 90); } } diff --git a/crates/handwriting-core/src/render/ink.rs b/crates/handwriting-core/src/render/ink.rs index fc41e754..7fa38a13 100644 --- a/crates/handwriting-core/src/render/ink.rs +++ b/crates/handwriting-core/src/render/ink.rs @@ -14,16 +14,16 @@ pub(super) fn normal(rng: &mut ChaCha8Rng, sigma: f32) -> f32 { } } pub(super) fn paste_mask(dest: &mut GrayImage, src: &GrayImage, x: i32, y: i32) { - for (xx, yy, p) in src.enumerate_pixels() { - let dx = x + xx as i32; - let dy = y + yy as i32; - if dx >= 0 && dy >= 0 && dx < dest.width() as i32 && dy < dest.height() as i32 { - dest[(dx as u32, dy as u32)][0] = dest[(dx as u32, dy as u32)][0].max(p[0]); + let width = dest.width() as usize; + for (dx, dy, row) in coverage::clipped_rows(src, dest.dimensions(), x, y) { + let start = dy * width + dx; + for (dst, &sample) in dest.as_mut()[start..start + row.len()].iter_mut().zip(row) { + *dst = (*dst).max(sample); } } } // 2026-10-12:四邻域连通区域整体扰动;旋转方向沿用 handright,算法许可见 NOTICE。 -pub(super) fn perturb( +pub(super) fn legacy_perturb( mask: &mut GrayImage, canvas: &mut RgbaImage, p: &Parameters, @@ -186,8 +186,12 @@ fn draw_paper_pattern(paper: &mut RgbaImage, p: &Parameters, pattern: PaperPatte } } +pub(crate) mod coverage; +mod text; +pub(super) use text::perturb; + mod rigid; -pub(super) use rigid::{RigidPlacement, paint_math_unit}; +pub(super) use rigid::{RigidPlacement, legacy_paint_math_unit, paint_math_unit}; #[cfg(test)] mod paper_tests { diff --git a/crates/handwriting-core/src/render/ink/coverage.rs b/crates/handwriting-core/src/render/ink/coverage.rs new file mode 100644 index 00000000..adc07e43 --- /dev/null +++ b/crates/handwriting-core/src/render/ink/coverage.rs @@ -0,0 +1,137 @@ +use image::{GrayImage, Rgba}; + +/// Contiguous source rows and their destination coordinates after clipping to the page. +pub(crate) fn clipped_rows( + mask: &GrayImage, + (width, height): (u32, u32), + x: i32, + y: i32, +) -> impl Iterator { + let dx = (x.max(0) as u32).min(width); + let dy = (y.max(0) as u32).min(height); + let sx = x.min(0).unsigned_abs().min(mask.width()); + let sy = y.min(0).unsigned_abs().min(mask.height()); + let count = (width - dx).min(mask.width() - sx) as usize; + let rows = (height - dy).min(mask.height() - sy); + (0..rows).map(move |row| { + let start = (sy + row) as usize * mask.width() as usize + sx as usize; + ( + dx as usize, + (dy + row) as usize, + &mask.as_raw()[start..start + count], + ) + }) +} + +/// Bilinear coverage at pixel-center coordinates. Samples outside the mask are transparent. +#[inline] +pub(crate) fn sample_coverage(mask: &GrayImage, x: f64, y: f64) -> u8 { + if x <= -1. || y <= -1. || x >= f64::from(mask.width()) || y >= f64::from(mask.height()) { + return 0; + } + let ix = if x < 0. { -1 } else { x as i32 }; + let iy = if y < 0. { -1 } else { y as i32 }; + let (fx, fy) = (x - f64::from(ix), y - f64::from(iy)); + let taps = + if ix >= 0 && iy >= 0 && ix as u32 + 1 < mask.width() && iy as u32 + 1 < mask.height() { + let stride = mask.width() as usize; + let row = iy as usize * stride + ix as usize; + let raw = mask.as_raw(); + [ + raw[row], + raw[row + 1], + raw[row + stride], + raw[row + stride + 1], + ] + } else { + let tap = |x: i32, y: i32| { + mask.get_pixel_checked(x as u32, y as u32) + .map_or(0, |p| p[0]) + }; + [ + tap(ix, iy), + tap(ix + 1, iy), + tap(ix, iy + 1), + tap(ix + 1, iy + 1), + ] + }; + interpolate(taps, fx, fy) +} + +/// The stamp has a one-pixel zero border, so all four taps can be read together. +/// Coordinates still refer to the unpadded stroke. +#[inline] +pub(super) fn sample_padded(stamp: &GrayImage, x: f64, y: f64) -> u8 { + // Truncation is floor for positive coordinates. In the interval (-1, 0) + // the left/top tap is the padding itself. More negative indices clip out. + let px = (x as i32).saturating_add(i32::from(x >= 0.)) as u32; + let py = (y as i32).saturating_add(i32::from(y >= 0.)) as u32; + if px >= stamp.width() - 1 || py >= stamp.height() - 1 { + return 0; + } + let stride = stamp.width() as usize; + let start = py as usize * stride + px as usize; + let samples = &stamp.as_raw()[start..start + stride + 2]; + let taps = [samples[0], samples[1], samples[stride], samples[stride + 1]]; + interpolate( + taps, + x - f64::from(px as i32 - 1), + y - f64::from(py as i32 - 1), + ) +} + +#[inline] +fn interpolate(taps: [u8; 4], fx: f64, fy: f64) -> u8 { + if taps == [0; 4] { + return 0; + } + let [a, b, c, d] = taps.map(f64::from); + let top = a * (1. - fx) + b * fx; + let bottom = c * (1. - fx) + d * fx; + (top * (1. - fy) + bottom * fy + 0.5) as u8 +} + +/// Apply the pen opacity and mask coverage once. +#[inline] +pub(super) fn blend_coverage(pixel: &mut Rgba, mut fill: Rgba, coverage: u8) { + fill[3] = ((u16::from(fill[3]) * u16::from(coverage) + 127) / 255) as u8; + crate::ink_effects::blend_ink(pixel, fill); +} + +#[cfg(test)] +mod tests { + use super::*; + use image::Luma; + + #[test] + fn padded_stroke_sampling_matches_the_unpadded_kernel() { + for (w, h) in [(1, 1), (1, 9), (7, 1), (13, 11)] { + let mask = + GrayImage::from_fn(w, h, |x, y| Luma([((173 * x + 119 * y + 33) % 256) as u8])); + let mut stamp = GrayImage::new(w + 2, h + 2); + image::imageops::replace(&mut stamp, &mask, 1, 1); + for y in -16..=(h as i32 + 1) * 8 { + for x in -16..=(w as i32 + 1) * 8 { + let (x, y) = (f64::from(x) / 8., f64::from(y) / 8.); + assert_eq!(sample_padded(&stamp, x, y), sample_coverage(&mask, x, y)); + } + } + } + } + + #[test] + fn interpolation_uses_transparent_neighbors_at_all_four_edges() { + let mask = GrayImage::from_pixel(1, 1, Luma([240])); + for (x, y, expected) in [ + (0., 0., 240), + (-0.5, 0., 120), + (0.5, 0., 120), + (0., -0.5, 120), + (0., 0.5, 120), + (0.5, -0.5, 60), + (-1., 0., 0), + ] { + assert_eq!(sample_coverage(&mask, x, y), expected); + } + } +} diff --git a/crates/handwriting-core/src/render/ink/rigid.rs b/crates/handwriting-core/src/render/ink/rigid.rs index b648f572..6adbad23 100644 --- a/crates/handwriting-core/src/render/ink/rigid.rs +++ b/crates/handwriting-core/src/render/ink/rigid.rs @@ -4,22 +4,28 @@ use image::Pixel; pub(in crate::render) struct RigidPlacement<'a> { pub origin: (i32, i32), pub align_to_rulings: bool, + pub protect_lines: bool, pub table_edge: &'a mut [i32], } -pub(in crate::render) fn paint_math_unit( - canvas: &mut RgbaImage, +struct RigidInk { + cx: f32, + cy: f32, + dx: f32, + dy: f32, + angle: f32, + bounds: (f32, f32, f32, f32), + fill: Rgba, +} + +fn place( + canvas: &RgbaImage, mask: &GrayImage, - placement: RigidPlacement<'_>, + origin: (i32, i32), + align_to_rulings: bool, p: &Parameters, rng: &mut ChaCha8Rng, - cancel: &Cancellation, -) -> Result<()> { - let RigidPlacement { - origin, - align_to_rulings, - table_edge, - } = placement; +) -> RigidInk { let cx = (mask.width() - 1) as f32 / 2.; let cy = (mask.height() - 1) as f32 / 2.; let sampled_angle = normal(rng, p.perturb_theta_sigma); @@ -68,6 +74,121 @@ pub(in crate::render) fn paint_math_unit( (p.fill[2] as f32 + ink).clamp(0., 255.) as u8, p.fill[3], ]); + RigidInk { + cx, + cy, + dx, + dy, + angle, + bounds: b, + fill, + } +} + +pub(in crate::render) fn paint_math_unit( + canvas: &mut RgbaImage, + mask: &GrayImage, + placement: RigidPlacement<'_>, + p: &Parameters, + rng: &mut ChaCha8Rng, + cancel: &Cancellation, +) -> Result<()> { + let RigidPlacement { + origin, + align_to_rulings, + protect_lines, + table_edge, + } = placement; + let ink = place(canvas, mask, origin, align_to_rulings, p, rng); + let (sin, cos) = ink.angle.sin_cos(); + let offset_x = origin.0 as f32 + ink.dx; + let offset_y = origin.1 as f32 + ink.dy; + // A bilinear tap reaches one source pixel beyond its center on each axis. + let fringe = cos.abs() + sin.abs(); + let (x0, y0, x1, y1) = ink.bounds; + let left = (offset_x + x0 - fringe).max(p.left_margin).max(0.).ceil() as u32; + let top = (offset_y + y0 - fringe).max(p.top_margin).max(0.).ceil() as u32; + let right = (offset_x + x1 + fringe) + .min(canvas.width() as f32 - 1. - p.effective_right_margin().max(0.)) + .floor() as u32; + let bottom = (offset_y + y1 + fringe) + .min(canvas.height() as f32 - 1. - p.bottom_margin.max(0.)) + .floor() as u32; + for y in top..=bottom { + if (y - top).is_multiple_of(32) { + cancel.check()?; + } + let ry = y as f32 - offset_y - ink.cy; + for x in left..=right { + let rx = x as f32 - offset_x - ink.cx; + let sx = rx * cos - ry * sin + ink.cx; + let sy = rx * sin + ry * cos + ink.cy; + let mut alpha = coverage::sample_coverage(mask, sx.into(), sy.into()); + if protect_lines && (1..128).contains(&alpha) { + alpha = alpha.max(wire_center(mask, sx, sy)); + } + if alpha == 0 { + continue; + } + coverage::blend_coverage(&mut canvas[(x, y)], ink.fill, alpha); + // Table clearance follows the transformed mask even when the pen is transparent. + if let Some(edge) = table_edge.get_mut(x as usize) { + *edge = (*edge).max(y as i32 + 1); + } + } + } + Ok(()) +} + +// A subpixel wire can cross a pixel between adjacent raster centers. Restore +// the coverage of that line segment only within its one-pixel-wide core. +fn wire_center(mask: &GrayImage, x: f32, y: f32) -> u8 { + let (ix, iy) = (x.floor() as i32, y.floor() as i32); + let (fx, fy) = (x - ix as f32, y - iy as f32); + let core = |dx: i32, dy: i32| { + mask.get_pixel_checked((ix + dx) as u32, (iy + dy) as u32) + .is_some_and(|p| p[0] >= 128) + }; + let (a, b, c, d) = (core(0, 0), core(1, 0), core(0, 1), core(1, 1)); + let diagonal = 0.5 * std::f32::consts::SQRT_2; + let inside = (a && b && fy <= 0.5) + || (c && d && fy >= 0.5) + || (a && c && fx <= 0.5) + || (b && d && fx >= 0.5) + || (a && d && (fx - fy).abs() <= diagonal) + || (b && c && (fx + fy - 1.).abs() <= diagonal); + let near = |dx: f32, dy: f32| dx * dx + dy * dy <= 0.25; + let cap = (a && near(fx, fy)) + || (b && near(1. - fx, fy)) + || (c && near(fx, 1. - fy)) + || (d && near(1. - fx, 1. - fy)); + if inside || cap { 128 } else { 0 } +} + +// Preserve tile coordinates of saved fine-edit documents. +pub(in crate::render) fn legacy_paint_math_unit( + canvas: &mut RgbaImage, + mask: &GrayImage, + placement: RigidPlacement<'_>, + p: &Parameters, + rng: &mut ChaCha8Rng, + cancel: &Cancellation, +) -> Result<()> { + let RigidPlacement { + origin, + align_to_rulings, + table_edge, + .. + } = placement; + let RigidInk { + cx, + cy, + dx, + dy, + angle, + fill, + .. + } = place(canvas, mask, origin, align_to_rulings, p, rng); let (sin, cos) = angle.sin_cos(); let project = |x: u32, y: u32| { let (rx, ry) = (x as f32 - cx, y as f32 - cy); @@ -145,6 +266,7 @@ mod tests { RigidPlacement { origin: (42, 44), align_to_rulings: false, + protect_lines: true, table_edge: &mut table_edge, }, &p, @@ -155,18 +277,63 @@ mod tests { let ink = GrayImage::from_fn(canvas.width(), canvas.height(), |x, y| { Luma([canvas[(x, y)][3]]) }); - assert_eq!( - table_edge.into_iter().max(), - ink.enumerate_pixels() - .filter(|(_, _, p)| p[0] > 0) - .map(|(_, y, _)| y as i32 + 1) - .max() - ); - let labels = connected_components(&ink, Connectivity::Eight, Luma([0])); + for (x, bottom) in table_edge.into_iter().enumerate() { + let last = (0..ink.height()).rfind(|&y| ink[(x as u32, y)][0] > 0); + assert_eq!(bottom, last.map_or(0, |y| y as i32 + 1)); + } + assert!(ink.pixels().any(|p| (1..=127).contains(&p[0]))); + let visible = GrayImage::from_fn(ink.width(), ink.height(), |x, y| { + Luma([u8::from(ink[(x, y)][0] >= 40)]) + }); + let labels = connected_components(&visible, Connectivity::Eight, Luma([0])); assert_eq!(labels.pixels().map(|p| p[0]).max(), Some(2), "seed {seed}"); } } + #[test] + fn unrotated_mask_scales_partial_coverage_by_pen_opacity() { + let mask = GrayImage::from_raw(5, 1, vec![0, 64, 127, 192, 255]).unwrap(); + let mut p = Parameters { + left_margin: 0., + right_margin: 0., + top_margin: 0., + bottom_margin: 0., + word_spacing: 0., + fill: [10, 20, 30, 128], + perturb_theta_sigma: 0., + perturb_x_sigma: 0., + perturb_y_sigma: 0., + ink_depth_sigma: 0., + ..Default::default() + }; + for (opacity, expected) in [ + (255, [0, 64, 127, 192, 255]), + (128, [0, 32, 64, 96, 128]), + (1, [0, 0, 0, 1, 1]), + (0, [0; 5]), + ] { + p.fill[3] = opacity; + let mut canvas = RgbaImage::new(5, 1); + let mut edge = [0; 5]; + paint_math_unit( + &mut canvas, + &mask, + RigidPlacement { + origin: (0, 0), + align_to_rulings: false, + protect_lines: false, + table_edge: &mut edge, + }, + &p, + &mut ChaCha8Rng::seed_from_u64(0), + &Cancellation::default(), + ) + .unwrap(); + assert_eq!(canvas.pixels().map(|p| p[3]).collect::>(), expected); + assert_eq!(edge, [0, 1, 1, 1, 1]); + } + } + #[test] fn locked_table_rules_stay_on_the_paper_axis_across_seeds() { let mut mask = GrayImage::new(201, 21); @@ -194,6 +361,7 @@ mod tests { RigidPlacement { origin: (60, 70), align_to_rulings: true, + protect_lines: false, table_edge: &mut [], }, &p, diff --git a/crates/handwriting-core/src/render/ink/text.rs b/crates/handwriting-core/src/render/ink/text.rs new file mode 100644 index 00000000..4bdcae35 --- /dev/null +++ b/crates/handwriting-core/src/render/ink/text.rs @@ -0,0 +1,524 @@ +//! Carry font rasterizer coverage with each independently perturbed four-connected stroke. +use super::coverage::{blend_coverage, sample_padded}; +use super::normal; +use crate::{Cancellation, Parameters, Result}; +use image::{GrayImage, Pixel, Rgba, RgbaImage}; +use rand_chacha::ChaCha8Rng; +use std::collections::VecDeque; + +#[derive(Clone, Copy)] +struct Bounds { + left: u32, + right: u32, + top: u32, + bottom: u32, +} + +impl Bounds { + fn full(mask: &GrayImage) -> Self { + Self { + left: 0, + right: mask.width() - 1, + top: 0, + bottom: mask.height() - 1, + } + } + + fn at(x: u32, y: u32) -> Self { + Self { + left: x, + right: x, + top: y, + bottom: y, + } + } + + fn include(&mut self, x: u32, y: u32) { + self.left = self.left.min(x); + self.right = self.right.max(x); + self.top = self.top.min(y); + self.bottom = self.bottom.max(y); + } + + fn center(self) -> (f64, f64) { + ( + (f64::from(self.left) + f64::from(self.right)) / 2., + (f64::from(self.top) + f64::from(self.bottom)) / 2., + ) + } +} + +struct Stroke { + center: (f64, f64), + bounds: Bounds, +} + +// The transparent border lets both floods visit neighboring cells with fixed offsets. +// Unclaimed cells retain source coverage (0..=255); assigned cells store their stroke ID. +const FIRST_STROKE: u32 = 256; + +struct Owners { + cells: Vec, + stride: usize, +} + +impl Owners { + fn row(&self, y: u32) -> &[u32] { + let start = (y as usize + 1) * self.stride + 1; + &self.cells[start..start + self.stride - 2] + } +} + +// Number solid cores in the original scan order. Grow all their weak fringes together so +// neighboring strokes keep separate transforms even when their antialiasing touches. +fn stroke_owners( + mask: &GrayImage, + band: Bounds, + cancel: &Cancellation, +) -> Result<(Owners, Vec)> { + let width = (band.right - band.left + 1) as usize; + let height = (band.bottom - band.top + 1) as usize; + let stride = width + 2; + let mut cells = vec![0; stride * (height + 2)]; + for (y, row) in cells + .chunks_exact_mut(stride) + .skip(1) + .take(height) + .enumerate() + { + cancel.check()?; + let offset = (band.top as usize + y) * mask.width() as usize + band.left as usize; + for (dst, &src) in row[1..width + 1] + .iter_mut() + .zip(&mask.as_raw()[offset..offset + width]) + { + *dst = u32::from(src); + } + } + let mut strokes = Vec::new(); + let mut core = Vec::new(); + let mut fringe = VecDeque::new(); + let mut visited = 0usize; + for y in 0..height { + cancel.check()?; + let start = (y + 1) * stride + 1; + for seed in start..start + width { + if !(128..=255).contains(&cells[seed]) { + continue; + } + let id = FIRST_STROKE + strokes.len() as u32; + let mut bounds = Bounds::at((seed - start) as u32, y as u32); + cells[seed] = id; + core.push(seed); + while let Some(pos) = core.pop() { + bounds.include((pos % stride - 1) as u32, (pos / stride - 1) as u32); + let up = pos - stride; + let down = pos + stride; + for adj in [up, down, pos - 1, pos + 1] { + match cells[adj] { + 128..=255 => { + cells[adj] = id; + core.push(adj); + } + 1..=127 => { + cells[adj] = id; + fringe.push_back(adj); + } + _ => (), + } + } + for adj in [up - 1, up + 1, down - 1, down + 1] { + if (1..128).contains(&cells[adj]) { + cells[adj] = id; + fringe.push_back(adj); + } + } + visited += 1; + if visited.is_multiple_of(8192) { + cancel.check()?; + } + } + strokes.push(Stroke { + center: bounds.center(), + bounds, + }); + } + } + while let Some(pos) = fringe.pop_front() { + let id = cells[pos]; + strokes[(id - FIRST_STROKE) as usize] + .bounds + .include((pos % stride - 1) as u32, (pos / stride - 1) as u32); + let up = pos - stride; + let down = pos + stride; + for adj in [ + up - 1, + up, + up + 1, + pos - 1, + pos + 1, + down - 1, + down, + down + 1, + ] { + if (1..128).contains(&cells[adj]) { + cells[adj] = id; + fringe.push_back(adj); + } + } + visited += 1; + if visited.is_multiple_of(8192) { + cancel.check()?; + } + } + Ok((Owners { cells, stride }, strokes)) +} + +struct Motion { + dx: f64, + dy: f64, + angle: f64, + fill: Rgba, +} + +impl Motion { + fn sample(p: &Parameters, rng: &mut ChaCha8Rng) -> Self { + let dx = normal(rng, p.perturb_x_sigma).into(); + let dy = normal(rng, p.perturb_y_sigma).into(); + let angle = normal(rng, p.perturb_theta_sigma).into(); + let ink = normal(rng, p.ink_depth_sigma); + let mut fill = Rgba(p.fill); + for channel in &mut fill.0[..3] { + *channel = (f32::from(*channel) + ink).clamp(0., 255.) as u8; + } + Self { + dx, + dy, + angle, + fill, + } + } +} + +fn paint_stroke( + canvas: &mut RgbaImage, + stamp: &GrayImage, // one transparent pixel of padding on every side + origin: (u32, u32), + pivot: (f64, f64), + motion: Motion, + cancel: &Cancellation, +) -> Result<()> { + let (ox, oy) = (f64::from(origin.0), f64::from(origin.1)); + let (cx, cy) = (pivot.0 - ox, pivot.1 - oy); + let (tx, ty) = (pivot.0 + motion.dx, pivot.1 + motion.dy); + let (sin, cos) = motion.angle.sin_cos(); + // The bilinear kernel has support one source pixel beyond each edge center. + let mut min_x = f64::INFINITY; + let mut min_y = f64::INFINITY; + let mut max_x = f64::NEG_INFINITY; + let mut max_y = f64::NEG_INFINITY; + for x in [-1., f64::from(stamp.width() - 2)] { + for y in [-1., f64::from(stamp.height() - 2)] { + let xx = (x - cx) * cos + (y - cy) * sin + tx; + let yy = (y - cy) * cos - (x - cx) * sin + ty; + min_x = min_x.min(xx); + min_y = min_y.min(yy); + max_x = max_x.max(xx); + max_y = max_y.max(yy); + } + } + let left = min_x.ceil() as usize; + let right = (max_x.floor() as usize) + .saturating_add(1) + .min(canvas.width() as usize); + if left >= right { + return Ok(()); + } + let width = canvas.width() as usize; + for y in min_y.ceil() as u32..=(max_y.floor() as u32).min(canvas.height() - 1) { + cancel.check()?; + let start = (y as usize * width + left) * 4; + let row = &mut canvas.as_mut()[start..start + (right - left) * 4]; + let (rx, ry) = (left as f64 - tx, f64::from(y) - ty); + let mut sx = rx * cos - ry * sin + cx; + let mut sy = rx * sin + ry * cos + cy; + for pixel in row.chunks_exact_mut(4) { + let coverage = sample_padded(stamp, sx, sy); + if coverage != 0 { + blend_coverage(Rgba::from_slice_mut(pixel), motion.fill, coverage); + } + sx += cos; + sy += sin; + } + } + Ok(()) +} + +fn paint_band( + mask: &mut GrayImage, + canvas: &mut RgbaImage, + band: Bounds, + p: &Parameters, + rng: &mut ChaCha8Rng, + cancel: &Cancellation, +) -> Result<()> { + let (owners, strokes) = stroke_owners(mask, band, cancel)?; + if p.perturb_x_sigma == 0. && p.perturb_y_sigma == 0. && p.perturb_theta_sigma == 0. { + let colors: Vec<_> = strokes + .iter() + .map(|_| Motion::sample(p, rng).fill) + .collect(); + return paint_in_place( + mask, + canvas, + band, + |x, y| { + let owner = owners.row(y - band.top)[(x - band.left) as usize]; + if owner < FIRST_STROKE { + Rgba(p.fill) + } else { + colors[(owner - FIRST_STROKE) as usize] + } + }, + cancel, + ); + } + let width = mask.width() as usize; + let mut scratch = Vec::new(); + for (index, stroke) in strokes.into_iter().enumerate() { + let b = stroke.bounds; + let id = FIRST_STROKE + index as u32; + let stamp_width = (b.right - b.left + 1) as usize; + let stamp_height = (b.bottom - b.top + 1) as usize; + let stride = stamp_width + 2; + scratch.resize(stride * (stamp_height + 2), 0); + scratch[..stride].fill(0); + scratch[(stamp_height + 1) * stride..].fill(0); + for (y, dst) in (b.top..=b.bottom).zip(scratch.chunks_exact_mut(stride).skip(1)) { + cancel.check()?; + let offset = (band.top + y) as usize * width + (band.left + b.left) as usize; + let row = &mut mask.as_mut()[offset..offset + stamp_width]; + let labels = &owners.row(y)[b.left as usize..=b.right as usize]; + dst[0] = 0; + dst[stride - 1] = 0; + for ((sample, &owner), coverage) in dst[1..stride - 1].iter_mut().zip(labels).zip(row) { + *sample = if owner == id { + std::mem::take(coverage) + } else { + 0 + }; + } + } + let stamp = GrayImage::from_raw(stride as u32, stamp_height as u32 + 2, scratch).unwrap(); + paint_stroke( + canvas, + &stamp, + (band.left + b.left, band.top + b.top), + ( + stroke.center.0 + f64::from(band.left), + stroke.center.1 + f64::from(band.top), + ), + Motion::sample(p, rng), + cancel, + )?; + scratch = stamp.into_raw(); + } + // Entirely faint marks have no historical perturbation draw. Preserve them in place + // without advancing the shared page RNG or leaving them in the next page's mask. + paint_in_place(mask, canvas, band, |_, _| Rgba(p.fill), cancel) +} + +fn paint_in_place( + mask: &mut GrayImage, + canvas: &mut RgbaImage, + band: Bounds, + fill: impl Fn(u32, u32) -> Rgba, + cancel: &Cancellation, +) -> Result<()> { + let width = mask.width() as usize; + for y in band.top..=band.bottom { + cancel.check()?; + let offset = y as usize * width; + let row = &mut mask.as_mut()[offset + band.left as usize..=offset + band.right as usize]; + for (x, sample) in (band.left..=band.right).zip(row) { + if *sample != 0 { + blend_coverage(&mut canvas[(x, y)], fill(x, y), std::mem::take(sample)); + } + } + } + Ok(()) +} + +pub(in crate::render) fn perturb( + mask: &mut GrayImage, + canvas: &mut RgbaImage, + p: &Parameters, + rng: &mut ChaCha8Rng, + cancel: &Cancellation, +) -> Result<()> { + if mask.is_empty() { + return Ok(()); + } + if p.perturb_x_sigma == 0. + && p.perturb_y_sigma == 0. + && p.perturb_theta_sigma == 0. + && p.ink_depth_sigma == 0. + { + return paint_in_place( + mask, + canvas, + Bounds::full(mask), + |_, _| Rgba(p.fill), + cancel, + ); + } + // Empty rows separate independent ink. Allocate labels only for the currently + // occupied band, and release them before continuing to the next lines of text. + let mut band = None; + for y in 0..mask.height() { + cancel.check()?; + let row_start = y as usize * mask.width() as usize; + let row = &mask.as_raw()[row_start..row_start + mask.width() as usize]; + if let Some(left) = row.iter().position(|&v| v != 0) { + let right = row.iter().rposition(|&v| v != 0).unwrap(); + let bounds = band.get_or_insert(Bounds::at(left as u32, y)); + bounds.left = bounds.left.min(left as u32); + bounds.right = bounds.right.max(right as u32); + bounds.bottom = y; + } else if let Some(bounds) = band.take() { + paint_band(mask, canvas, bounds, p, rng, cancel)?; + } + } + if let Some(bounds) = band { + paint_band(mask, canvas, bounds, p, rng, cancel)?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use image::Luma; + use rand::{Rng, SeedableRng}; + + #[test] + fn identity_keeps_all_coverages_and_clears_the_reusable_page_mask() { + for depth in [0., 2.] { + let mut mask = + GrayImage::from_fn(256, 2, |x, y| Luma([if y == 1 { x as u8 } else { 0 }])); + let mut canvas = RgbaImage::new(256, 2); + let params = Parameters { + fill: [30, 80, 70, 153], + perturb_x_sigma: 0., + perturb_y_sigma: 0., + perturb_theta_sigma: 0., + ink_depth_sigma: depth, + ..Parameters::default() + }; + perturb( + &mut mask, + &mut canvas, + ¶ms, + &mut ChaCha8Rng::seed_from_u64(1), + &Cancellation::default(), + ) + .unwrap(); + for x in 0..256 { + assert_eq!( + canvas[(x, 1)][3], + ((x * 153 + 127) / 255) as u8, + "coverage {x}" + ); + assert_eq!(canvas[(x, 0)][3], 0); + } + assert!(mask.as_raw().iter().all(|&v| v == 0)); + } + } + + #[test] + fn fringe_uses_nearest_core_with_stable_ties_and_core_pivots() { + let mask = GrayImage::from_raw( + 9, + 3, + vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 200, 20, 20, 20, 200, 0, 0, 0, 0, 200, 0, 0, 0, 0, + 200, 0, 9, + ], + ) + .unwrap(); + let (owners, strokes) = + stroke_owners(&mask, Bounds::full(&mask), &Cancellation::default()).unwrap(); + assert_eq!(strokes.len(), 3); + assert_eq!(owners.row(1)[2], FIRST_STROKE); + assert_eq!(owners.row(1)[3], FIRST_STROKE); + assert_eq!(owners.row(1)[4], FIRST_STROKE + 1); + assert_eq!(owners.row(2)[6], FIRST_STROKE + 2); + assert_eq!(owners.row(2)[8], 9); + assert_eq!(strokes[0].center, (1., 1.5)); + assert_eq!(strokes[1].center, (5., 1.)); + } + + #[test] + fn faint_only_marks_survive_without_changing_the_seeded_core_draws() { + let p = Parameters::default(); + let mut mask = GrayImage::new(50, 50); + mask[(20, 10)][0] = 200; + mask[(15, 10)][0] = 33; + mask[(21, 11)][0] = 250; // diagonal solid neighbors are distinct cores + mask[(5, 40)][0] = 101; // disconnected, entirely faint row + let mut old_rng = ChaCha8Rng::seed_from_u64(42); + let mut rng = old_rng.clone(); + super::super::legacy_perturb( + &mut mask.clone(), + &mut RgbaImage::new(50, 50), + &p, + &mut old_rng, + &Cancellation::default(), + ) + .unwrap(); + let mut canvas = RgbaImage::new(50, 50); + perturb( + &mut mask, + &mut canvas, + &p, + &mut rng, + &Cancellation::default(), + ) + .unwrap(); + assert_eq!(rng.next_u64(), old_rng.next_u64()); + assert_eq!(canvas[(5, 40)][3], 101); + assert!(mask.as_raw().iter().all(|&v| v == 0)); + } + + #[test] + fn rotated_stroke_samples_subpixel_coverage_once_per_destination() { + let stamp = + GrayImage::from_raw(5, 3, vec![0, 0, 0, 0, 0, 0, 64, 240, 128, 0, 0, 0, 0, 0, 0]) + .unwrap(); + let mut canvas = RgbaImage::new(8, 8); + let motion = Motion { + dx: 0.5, + dy: 0., + angle: std::f64::consts::FRAC_PI_2, + fill: Rgba([0, 0, 0, 255]), + }; + paint_stroke( + &mut canvas, + &stamp, + (2, 3), + (3., 3.), + motion, + &Cancellation::default(), + ) + .unwrap(); + for (x, y, pixel) in canvas.enumerate_pixels() { + let expected = match (x, y) { + (3 | 4, 2) => 64, + (3 | 4, 3) => 120, + (3 | 4, 4) => 32, + _ => 0, + }; + assert_eq!(pixel[3], expected, "at {x}, {y}"); + } + } +} diff --git a/crates/handwriting-core/src/render/line.rs b/crates/handwriting-core/src/render/line.rs index fc031516..5e335765 100644 --- a/crates/handwriting-core/src/render/line.rs +++ b/crates/handwriting-core/src/render/line.rs @@ -1,7 +1,6 @@ //! Vertical placement of buffered ink, including formulas spanning multiple paper rulings. use super::LineUnit; use crate::{LayoutStyle, Parameters}; -use image::GrayImage; pub(super) struct LineLayout { top: f32, @@ -9,12 +8,18 @@ pub(super) struct LineLayout { gap: f32, spacing: f32, ruled: bool, + legacy: bool, min_y: i32, max_y: i32, } impl LineLayout { - pub(super) fn fit(units: &mut [LineUnit], p: &Parameters, page_height: u32) -> Self { + pub(super) fn fit( + units: &mut [LineUnit], + p: &Parameters, + page_height: u32, + legacy: bool, + ) -> Self { let top = p.top_margin; let bottom = page_height as f32 - p.bottom_margin; let available = (bottom - top).max(1.); @@ -24,14 +29,14 @@ impl LineLayout { let (mut min_y, mut max_y) = ink_bounds(units); if (max_y - min_y) as f32 > available { let factor = available / (max_y - min_y) as f32; - scale_units(units, min_y, factor, f32::floor); + scale_units(units, min_y, factor, f32::floor, legacy); (min_y, max_y) = ink_bounds(units); } if ruled && p.layout_style == LayoutStyle::Standard { gap = gap.min((p.line_spacing - p.font_size).max(2.)); let height = (p.line_spacing - gap).floor() as i32; let descent = (p.font_size * 0.30).round() as i32; - if fit_standard_ruled_row(units, min_y, max_y, height, descent) { + if fit_standard_ruled_row(units, min_y, max_y, height, descent, legacy) { (min_y, max_y) = ink_bounds(units); } } @@ -41,6 +46,7 @@ impl LineLayout { gap, spacing: p.line_spacing, ruled, + legacy, min_y, max_y, } @@ -97,7 +103,7 @@ impl LineLayout { best = (factor, baseline); } } - scale_units(units, 0, best.0, f32::round); + scale_units(units, 0, best.0, f32::round, self.legacy); (self.min_y, self.max_y) = ink_bounds(units); best.1 } @@ -105,7 +111,12 @@ impl LineLayout { // 2026-11-28:按栏比较表格落笔边界和下一行字形。笔尖轻触表框可以保留, // 一个字有三分之一以上的墨迹进入表内才重新安排该行。 -pub(super) fn intrudes_on_table(units: &[LineUnit], anchor: f32, edge: &[i32]) -> bool { +pub(super) fn intrudes_on_table( + units: &[LineUnit], + anchor: f32, + edge: &[i32], + legacy: bool, +) -> bool { units.iter().filter(|u| u.glyph.ink).any(|unit| { let x = unit.x + unit.glyph.left; let y = anchor.round() as i32 + unit.dy + unit.glyph.top; @@ -117,13 +128,18 @@ pub(super) fn intrudes_on_table(units: &[LineUnit], anchor: f32, edge: &[i32]) - } let mut ink = 0u64; let mut inside = 0u64; - for (dx, dy, _) in mask.enumerate_pixels().filter(|(_, _, p)| p[0] >= 128) { - ink += 1; + for (dx, dy, pixel) in mask.enumerate_pixels() { + let weight = if legacy { + u64::from(pixel[0] >= 128) + } else { + u64::from(pixel[0]) + }; + ink += weight; if edge .get((x + dx as i32) as usize) .is_some_and(|bottom| *bottom > 0 && y + (dy as i32) < *bottom) { - inside += 1; + inside += weight; } } ink > 0 && inside * 3 >= ink @@ -142,12 +158,18 @@ fn ink_bounds(units: &[LineUnit]) -> (i32, i32) { } // Page-height fitting starts at the visible top; fitting to a ruling preserves the baseline. -fn scale_units(units: &mut [LineUnit], origin: i32, factor: f32, round: fn(f32) -> f32) { +fn scale_units( + units: &mut [LineUnit], + origin: i32, + factor: f32, + round: fn(f32) -> f32, + legacy: bool, +) { for unit in units { let offset = unit.glyph.top + unit.dy - origin; let width = unit.glyph.mask.width() as f32 * factor; let height = (unit.glyph.mask.height() as f32 * factor).max(1.); - unit.glyph.fit_in_place(width, height); + unit.glyph.fit_in_place(width, height, legacy); unit.dy = round(offset as f32 * factor) as i32 - unit.glyph.top; } } @@ -158,6 +180,7 @@ fn fit_standard_ruled_row( max_y: i32, height: i32, descent: i32, + legacy: bool, ) -> bool { let ink_height = max_y - min_y; let top = descent - height; @@ -178,13 +201,8 @@ fn fit_standard_ruled_row( let last = (end * fit_height + ink_height - 1) / ink_height; let new_height = (last - first) as u32; if new_height != unit.glyph.mask.height() { - let mut mask = GrayImage::new(unit.glyph.mask.width(), new_height); - // 2026-11-17:合并缩小后落在同一行的像素,保留分数线等细笔画。 - for (x, y, pixel) in unit.glyph.mask.enumerate_pixels() { - let row = (y * new_height) / unit.glyph.mask.height(); - mask[(x, row)][0] = mask[(x, row)][0].max(pixel[0]); - } - unit.glyph.mask = mask; + unit.glyph + .resize_mask(unit.glyph.mask.width(), new_height, legacy); } unit.dy = start + first - unit.glyph.top; } diff --git a/crates/handwriting-core/tests/compact_math.rs b/crates/handwriting-core/tests/compact_math.rs index 2b7e5d2c..9e9f750d 100644 --- a/crates/handwriting-core/tests/compact_math.rs +++ b/crates/handwriting-core/tests/compact_math.rs @@ -136,35 +136,54 @@ fn nonzero_translation_moves_whole_formula_without_detaching_ink_components() { shifted.params.perturb_y_sigma = 3.; shifted.params.seed = seed; let actual = ink_crop(&page(&shifted), grid); - if source.contains('√') || source.contains(")/(") { - // 2026-10-24:分数线与根顶允许两像素内的自然曲线,不能让结构或字形独立漂移。 - assert!(actual.width().abs_diff(baseline.width()) <= 2); - assert!(actual.height().abs_diff(baseline.height()) <= 2); - for (a, b) in [(&baseline, &actual), (&actual, &baseline)] { - for (x, y, _) in a.enumerate_pixels().filter(|(_, _, p)| p[0] < 128) { - assert!( - (-2..=2).any(|dx| (-2..=2).any(|dy| { - let (xx, yy) = (x as i32 + dx, y as i32 + dy); - xx >= 0 - && yy >= 0 - && xx < b.width() as i32 - && yy < b.height() as i32 - && b[(xx as u32, yy as u32)][0] < 128 - })), - "{source}/{seed}: formula components moved independently" - ); - } - } + // A fractional translation shares coverage between adjacent samples. + // Only hand-drawn fraction bars and radical roofs may vary by two pixels. + let radius = if source.contains('√') || source.contains(")/(") { + 2 } else { + 1 + }; + for (a, b) in [(&baseline, &actual), (&actual, &baseline)] { assert!( - actual == baseline, - "{source}/{seed}: compound ink must translate as one unit" + a.width().abs_diff(b.width()) <= 2 && a.height().abs_diff(b.height()) <= 2, + "{source}/{seed}: compound bounds changed" ); + for (x, y, _) in a.enumerate_pixels().filter(|(_, _, p)| p[0] < 128) { + assert!( + (-radius..=radius).any(|dx| (-radius..=radius).any(|dy| { + b.get_pixel_checked((x as i32 + dx) as u32, (y as i32 + dy) as u32) + .is_some_and(|p| p[0] < 224) + })), + "{source}/{seed}: unmatched ink at ({x}, {y})" + ); + } } } } } +#[test] +fn monospaced_ink_is_clipped_to_the_physical_page_with_spacing_compensation() { + let mut req = request("湖湖湖湖湖湖湖"); + req.params.width = Some(120); + req.params.height = Some(120); + req.params.left_margin = 0.; + req.params.right_margin = 0.; + req.params.top_margin = 0.; + req.params.bottom_margin = 0.; + req.params.font_size = 20.; + req.params.line_spacing = 30.; + req.params.word_spacing = 10.; + req.params.monospaced = true; + let image = page(&req); + assert_eq!(image.dimensions(), (120, 120)); + assert!( + image + .enumerate_pixels() + .any(|(x, _, p)| x >= 100 && p[0] < 128) + ); +} + #[test] fn rotated_compound_ink_stays_inside_paper_margins() { for source in [ @@ -194,3 +213,49 @@ fn rotated_compound_ink_stays_inside_paper_margins() { } } } + +#[test] +fn subscript_and_superscript_share_one_subpixel_translation() { + let mut req = request(" xₙ²"); + let base = page(&req); + let centroid = |img: &RgbaImage| { + let (mut mass, mut mx, mut my) = (0., 0., 0.); + for (x, y, p) in img.enumerate_pixels() { + let ink = f64::from(255 - p[0]); + mass += ink; + mx += ink * f64::from(x); + my += ink * f64::from(y); + } + (mx / mass, my / mass) + }; + let (cx, cy) = centroid(&base); + let mut fractional = false; + req.params.perturb_x_sigma = 2.; + req.params.perturb_y_sigma = 3.; + for seed in 1..=8 { + req.params.seed = seed; + let shifted = page(&req); + let (nx, ny) = centroid(&shifted); + let (dx, dy) = (nx - cx, ny - cy); + fractional |= (dx - dx.round()).abs() > 0.1 || (dy - dy.round()).abs() > 0.1; + let mut max_error = 0.; + for (x, y, p) in shifted.enumerate_pixels() { + let (sx, sy) = (f64::from(x) - dx, f64::from(y) - dy); + let (ix, iy) = (sx.floor() as i32, sy.floor() as i32); + let (fx, fy) = (sx - sx.floor(), sy - sy.floor()); + let mut expected = 0.; + for (xx, wx) in [(ix, 1. - fx), (ix + 1, fx)] { + for (yy, wy) in [(iy, 1. - fy), (iy + 1, fy)] { + let sample = base.get_pixel_checked(xx as u32, yy as u32); + expected += sample.map_or(255., |p| f64::from(p[0])) * wx * wy; + } + } + max_error = f64::max(max_error, (expected - f64::from(p[0])).abs()); + } + assert!( + max_error <= 5., + "seed {seed}, peak coverage error {max_error}" + ); + } + assert!(fractional, "translations were rounded to whole pixels"); +} diff --git a/crates/handwriting-core/tests/generation_pipeline.rs b/crates/handwriting-core/tests/generation_pipeline.rs index f7cd6d21..8573ad7e 100644 --- a/crates/handwriting-core/tests/generation_pipeline.rs +++ b/crates/handwriting-core/tests/generation_pipeline.rs @@ -443,7 +443,7 @@ fn fine_edit_moves_one_homework_character_and_exports_the_same_pages() { scale: 115, angle: 12, opacity: 83, - opacity_ramp: None, + opacity_ramp: Some(fine_edit::OpacityRamp([[15, 30], [75, 90]])), color: Some([167, 12, 36]), thickness: 7, warp: Some([1., 0., 0., 0., 1., 0., 0.004, 0.]), @@ -647,3 +647,64 @@ fn photo_camera_tags_and_manual_fallback_survive_page_exports() { ) .unwrap(); } + +#[test] +fn table_clearance_keeps_its_pagination_at_every_pen_opacity() { + let mut req = request("⟦ X | 0 1 ; ── ; P | ⅓ ⅔ ⟧\n草草草草草"); + req.params.height = Some(160); + req.params.seed = 0; + req.params.perturb_x_sigma = 1.5; + req.params.perturb_y_sigma = 18.; + req.params.perturb_theta_sigma = 0.35; + for opacity in [255, 8, 0] { + req.params.fill[3] = opacity; + let count = render::count_pages(&req, &Cancellation::default()).unwrap(); + assert_eq!(count, 2, "pen opacity {opacity}"); + } +} + +#[test] +fn saved_keys_reopen_their_original_tile_coordinates() { + use fine_edit::Adjustments; + use sha2::{Digest, Sha256}; + let mut req = request("京A。\n⟦ X | 0 1 ; ── ; P | ⅓ ⅔ ⟧\n草e"); + req.params.fine_edit = true; + req.params.height = Some(340); + req.params.seed = 2; + req.params.perturb_x_sigma = 1.5; + req.params.perturb_y_sigma = 6.; + req.params.perturb_theta_sigma = 0.25; + for version in ["panache-fine-2", "panache-fine-3"] { + let mut hash = Sha256::new(); + hash.update(version.as_bytes()); + hash.update([0]); + hash.update(req.text.as_bytes()); + hash.update([0; 3]); + let key = format!("{:x}", hash.finalize()); + req.params.fine_edits = Some(Adjustments { + key: key.clone(), + glyphs: vec![], + }); + let (actual_key, items) = + fine_edit::inspect_page(&req, 1, &Cancellation::default()).unwrap(); + assert_eq!(actual_key, key); + let geometry: Vec<_> = items + .into_iter() + .map(|g| (g.id, g.bounds, g.baseline)) + .collect(); + // Golden paper coordinates from 56239e8, before mask coverage changed the crop. + // The tilted table pushes the next line down only under fine-3. + let dy = if version == "panache-fine-3" { 17 } else { 0 }; + assert_eq!( + geometry, + [ + (0, [10, 21, 26, 37], 46), + (1, [31, 29, 24, 25], 46), + (2, [52, 42, 15, 15], 46), + (4, [-2, 53, 107, 118], 100), + (6, [6, 150 + dy, 31, 29], 173 + dy), + (7, [30, 161 + dy, 22, 20], 173 + dy), + ] + ); + } +} diff --git a/crates/handwriting-core/tests/ink_coverage.rs b/crates/handwriting-core/tests/ink_coverage.rs new file mode 100644 index 00000000..9399f33f --- /dev/null +++ b/crates/handwriting-core/tests/ink_coverage.rs @@ -0,0 +1,94 @@ +use handwriting_core::{Cancellation, FontBook, Limits, Parameters, RenderRequest, render}; +use image::{GrayImage, Luma}; +use std::{fs, path::Path}; + +fn crop_ink(mask: &GrayImage) -> GrayImage { + let mut bounds = (mask.width(), mask.height(), 0, 0); + for (x, y, _) in mask.enumerate_pixels().filter(|(_, _, p)| p[0] != 0) { + bounds = ( + bounds.0.min(x), + bounds.1.min(y), + bounds.2.max(x + 1), + bounds.3.max(y + 1), + ); + } + let (x, y, right, bottom) = bounds; + assert!(right > x && bottom > y); + image::imageops::crop_imm(mask, x, y, right - x, bottom - y).to_image() +} + +#[test] +fn transparent_page_preserves_font_coverage_through_each_render_path() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/font_assets/云烟体.ttf"); + let font = FontBook::load(&fs::read(path).unwrap()).unwrap(); + let (metrics, pixels) = font.rasterize('湖', 40.); + let raw = GrayImage::from_raw(metrics.width as u32, metrics.height as u32, pixels).unwrap(); + let fonts = FontBook::from_fonts(font, vec![]); + for (ink_layers, fine_edit) in [(false, false), (true, false), (false, true)] { + for opacity in [255, 128] { + let expected = GrayImage::from_fn(raw.width(), raw.height(), |x, y| { + Luma([((u32::from(raw[(x, y)][0]) * u32::from(opacity) + 127) / 255) as u8]) + }); + let request = RenderRequest { + text: "湖".into(), + fonts: fonts.clone(), + background: None, + limits: Limits::default(), + params: Parameters { + width: Some(320), + height: Some(320), + font_size: 40., + line_spacing: 75., + ink_layers, + fine_edit, + transparent_background: true, + fill: [33, 66, 99, opacity], + font_size_sigma: 0., + perturb_x_sigma: 0., + perturb_y_sigma: 0., + perturb_theta_sigma: 0., + ink_depth_sigma: 0., + strikethrough_probability: 0., + ..Parameters::default() + }, + }; + let mut reference = None; + let pages = render(&request, &Cancellation::default(), |_, page| { + assert!( + page.pixels() + .filter(|p| p[3] != 0) + .all(|p| p.0[..3] == [33, 66, 99]) + ); + let alpha = + GrayImage::from_fn(page.width(), page.height(), |x, y| Luma([page[(x, y)][3]])); + let actual = crop_ink(&alpha); + let expected = crop_ink(&expected); + assert_eq!(actual.dimensions(), expected.dimensions()); + assert!( + actual == expected, + "font coverage changed: layered={ink_layers}, fine={fine_edit}, alpha={opacity}" + ); + reference = Some(page); + Ok(()) + }) + .unwrap(); + assert_eq!(pages, 1); + let mut white_paper = request; + white_paper.params.transparent_background = false; + let transparent = reference.unwrap(); + render(&white_paper, &Cancellation::default(), |_, paper| { + for (actual, ink) in paper.pixels().zip(transparent.pixels()) { + let alpha = u32::from(ink[3]); + for (channel, pen) in actual.0[..3].iter().zip([33u32, 66, 99]) { + assert_eq!( + u32::from(*channel), + (255 * (255 - alpha) + pen * alpha + 127) / 255 + ); + } + } + Ok(()) + }) + .unwrap(); + } + } +} diff --git a/docs/flutter-architecture.md b/docs/flutter-architecture.md index 9a098784..00685b22 100644 --- a/docs/flutter-architecture.md +++ b/docs/flutter-architecture.md @@ -65,6 +65,8 @@ PDF 工作台由 `screens/pdf_workbench.dart` 管理文档、页面缓存、编 `Workspace.edit()` 延迟 400 ms 保存;`persist()` 立即捕获当前快照并加入串行写入队列,后写快照不能被较慢的旧写覆盖。移动应用进入 inactive、paused 或 detached 时由页面调用 `persist()`;`dispose()` 也提交最后快照并关闭 API。操作系统强制结束进程无法保证执行 Dart 清理回调,主动生命周期保存用于减小丢失窗口。 +精调草稿在主快照中保留当前布局、调整参数和引擎提供的旧版布局键。`flutter.workspace.fine` 保存旧客户端重写快照时无法保留的布局信息和透明度渐变。旧版仅重存草稿时,新版可恢复原布局;旧版修改了调整参数时,保留旧布局与最新调整,仅给仍存在且参数相同的字块恢复渐变。被删除的调整不会恢复。新版需要从支持回退键的引擎取得对应页面,才能为此前保存的 fine-4 草稿补齐旧版布局键。 + 恢复草稿时按字段校验类型,损坏设置或插图条目不会清空其它可读内容。持久化实现可在测试中替换为内存实现,覆盖写入顺序、失败恢复和退出保存。 ## 任务与资源