Files
BadNote/lib/editor/engine/stroke_model.dart

213 lines
7.4 KiB
Dart
Raw Normal View History

// lib/editor/engine/stroke_model.dart
//
// Canonical, persistable stroke model for the BadNote editor engine.
//
// This is the single source of truth for ink strokes across the new own-canvas
// engine (screen render + export + persistence). It is a deliberate SUPERSET of
// both the in-memory live `PenStroke`/`PenPoint` (lib/editor/canvas/pen_stroke.dart)
// and the freezed/JSON `InkStroke`/`InkPoint` (lib/models/ink_stroke.dart) so the
// adapters below round-trip losslessly with `InkStroke` (SF1): `tilt`,
// `timestamp` and `pointerDeviceKind` are preserved, never dropped.
//
// Coordinate semantics (matching the live conventions):
// * Point x/y are NORMALIZED to the page rectangle, i.e. in [0,1].
// * Stroke `width` is a FRACTION of the page width, so it scales with zoom.
// @JsonKey is applied to freezed factory parameters (e.g. EditorStroke.brush)
// for fine-grained serialization control; freezed re-emits those annotations on
// generated getters where they're valid, so suppress the source-level
// invalid_annotation_target for the whole file (the documented freezed pattern).
// ignore_for_file: invalid_annotation_target
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:uuid/uuid.dart';
import '../../models/ink_point.dart';
import '../../models/ink_stroke.dart';
import '../../models/pen_tool.dart';
import '../../models/pointer_device_kind.dart';
import '../canvas/pen_stroke.dart';
import 'brush.dart';
part 'stroke_model.freezed.dart';
part 'stroke_model.g.dart';
const _uuid = Uuid();
/// The drawing tools the engine knows about. Extensible; P0 uses these three.
enum EditorTool {
@JsonValue('pen')
pen,
@JsonValue('highlighter')
highlighter,
@JsonValue('eraser')
eraser,
}
/// A single captured sample of a stroke.
///
/// [x]/[y] are normalized to the page rectangle ([0,1]). The remaining fields
/// are a superset of [InkPoint] (nullable here so the live capture path can
/// leave them unset, while [InkStroke] data round-trips intact through the
/// adapters below).
@freezed
abstract class EditorPoint with _$EditorPoint {
const factory EditorPoint({
required double x,
required double y,
double? pressure,
double? tilt,
int? timestamp,
InputDeviceKind? pointerDeviceKind,
}) = _EditorPoint;
factory EditorPoint.fromJson(Map<String, dynamic> json) =>
_$EditorPointFromJson(json);
}
/// A committed stroke in normalized page coordinates.
///
/// [width] is a fraction of page width (matches live `PenStroke.width`).
@freezed
abstract class EditorStroke with _$EditorStroke {
const EditorStroke._();
factory EditorStroke({
required String id,
required List<EditorPoint> points,
@Default(EditorTool.pen) EditorTool tool,
@Default(0xFF000000) int color,
@Default(0.003) double width,
@Default(false) bool filled,
String? textContent,
@Default(14.0) double fontSize,
// Brush the stroke was drawn with — drives the committed render path's
// perfect_freehand geometry + opacity/blend (resolveStrokePaint). Persisted
// as the stable `BrushKind` @JsonValue name (e.g. "ballpoint") so a
// ballpoint/highlighter/pencil stroke keeps its look across close/reopen.
// BACK-COMPAT: sidecars written before this field existed have no `brush`
// key, and an unknown name (a future brush opened by an older build) is
// tolerated — both fall back to fountainPen via the JsonKey below.
@JsonKey(
defaultValue: BrushKind.fountainPen,
unknownEnumValue: BrushKind.fountainPen,
)
@Default(BrushKind.fountainPen)
BrushKind brush,
}) = _EditorStroke;
/// Convenience constructor that generates a uuid [id] when none is supplied.
factory EditorStroke.create({
String? id,
required List<EditorPoint> points,
EditorTool tool = EditorTool.pen,
int color = 0xFF000000,
double width = 0.003,
bool filled = false,
String? textContent,
double fontSize = 14.0,
BrushKind brush = BrushKind.fountainPen,
}) =>
EditorStroke(
id: id ?? _uuid.v4(),
points: points,
tool: tool,
color: color,
width: width,
filled: filled,
textContent: textContent,
fontSize: fontSize,
brush: brush,
);
factory EditorStroke.fromJson(Map<String, dynamic> json) =>
_$EditorStrokeFromJson(json);
// ---- Adapters -----------------------------------------------------------
feat(pen): pressure-responsive width, configurable thinning, native Windows pen (tilt/buttons) W1 — Custom pen width + pressure sensitivity (Saber-style): - Root cause of "压感没用": perfect_freehand 1.0.4 IGNORES real stylus pressure (hardcodes radius=size/2 when simulatePressure=false) — width never tracked pen force. Upgraded perfect_freehand ^1.0.0 -> ^2.0.0 (honors real pressure); migrated all 5 getStroke call sites to the 2.x API (PointVector / StrokeOptions / Offset). - De-hardcoded `thinning` into `kDefaultPenThinning` (0.85), single source shared by the on-screen painter and the PDF export path; exposed as PenConfig.pressureSensitivity with a Pressure Sensitivity slider; live-applies via a config listener. W3 — Native Windows pen plugin (tilt + barrel/eraser buttons): - windows/runner/pen_channel.{h,cpp}: observe WM_POINTER at the TOP of MessageHandler (before HandleTopLevelWindowProc, which Flutter uses to consume pen events), read GetPointerPenInfo penFlags + tilt, stream over EventChannel('badnote/pen'); non-consuming. - PenInputService: single latched hardware state (no Win32-pointerId<->event.pointer correlation); graceful no-op off-Windows. - pen_canvas maps barrel/inverted/eraser through PenConfig.sideButton/eraserEnd (eraser/undo/toggleTool/pan) and captures tilt into PenPoint.tilt -> EditorPoint.tilt. W2 — Zoom flicker: page raster isolated in its own RepaintBoundary (safe interim); definitive crisp-on-zoom fix gated on the on-device root-cause probe (plan M3). Plans: ralplan-consensus plan at docs/plans/2026-06-22-badnote-pen-polish.md (Architect APPROVE-WITH-MUST-FIX M1-M4 + Critic ITERATE->APPROVE). Tests: 58/58 pass incl. shared-thinning invariant + thinning-affects-outline + tilt-adapter round-trip. flutter analyze clean; linux debug build OK. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 02:10:05 +08:00
/// Adapts an in-memory live [PenStroke] (normalized; carries tilt when the
/// native pen plugin supplied it, else null; no timestamp/pointerDeviceKind).
factory EditorStroke.fromPenStroke(PenStroke stroke, {String? id}) =>
EditorStroke(
id: id ?? _uuid.v4(),
points: stroke.points
feat(pen): pressure-responsive width, configurable thinning, native Windows pen (tilt/buttons) W1 — Custom pen width + pressure sensitivity (Saber-style): - Root cause of "压感没用": perfect_freehand 1.0.4 IGNORES real stylus pressure (hardcodes radius=size/2 when simulatePressure=false) — width never tracked pen force. Upgraded perfect_freehand ^1.0.0 -> ^2.0.0 (honors real pressure); migrated all 5 getStroke call sites to the 2.x API (PointVector / StrokeOptions / Offset). - De-hardcoded `thinning` into `kDefaultPenThinning` (0.85), single source shared by the on-screen painter and the PDF export path; exposed as PenConfig.pressureSensitivity with a Pressure Sensitivity slider; live-applies via a config listener. W3 — Native Windows pen plugin (tilt + barrel/eraser buttons): - windows/runner/pen_channel.{h,cpp}: observe WM_POINTER at the TOP of MessageHandler (before HandleTopLevelWindowProc, which Flutter uses to consume pen events), read GetPointerPenInfo penFlags + tilt, stream over EventChannel('badnote/pen'); non-consuming. - PenInputService: single latched hardware state (no Win32-pointerId<->event.pointer correlation); graceful no-op off-Windows. - pen_canvas maps barrel/inverted/eraser through PenConfig.sideButton/eraserEnd (eraser/undo/toggleTool/pan) and captures tilt into PenPoint.tilt -> EditorPoint.tilt. W2 — Zoom flicker: page raster isolated in its own RepaintBoundary (safe interim); definitive crisp-on-zoom fix gated on the on-device root-cause probe (plan M3). Plans: ralplan-consensus plan at docs/plans/2026-06-22-badnote-pen-polish.md (Architect APPROVE-WITH-MUST-FIX M1-M4 + Critic ITERATE->APPROVE). Tests: 58/58 pass incl. shared-thinning invariant + thinning-affects-outline + tilt-adapter round-trip. flutter analyze clean; linux debug build OK. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 02:10:05 +08:00
.map((p) =>
EditorPoint(x: p.x, y: p.y, pressure: p.pressure, tilt: p.tilt))
.toList(),
tool: switch (stroke.kind) {
PenStrokeKind.pen => EditorTool.pen,
PenStrokeKind.highlighter => EditorTool.highlighter,
},
color: stroke.color,
width: stroke.width,
brush: stroke.brush,
);
/// Lossless adapter from the freezed/JSON [InkStroke] model.
factory EditorStroke.fromInkStroke(InkStroke stroke) => EditorStroke(
id: stroke.id,
points: stroke.points
.map(
(p) => EditorPoint(
x: p.x,
y: p.y,
pressure: p.pressure,
tilt: p.tilt,
timestamp: p.timestamp,
pointerDeviceKind: p.pointerDeviceKind,
),
)
.toList(),
tool: _toolFromPenTool(stroke.tool),
color: stroke.color,
width: stroke.strokeWidth,
filled: stroke.filled,
textContent: stroke.textContent,
fontSize: stroke.fontSize,
// InkStroke has no brush field; derive from the tool so a loaded
// highlighter keeps the flat highlighter brush (pens → fountainPen).
brush: stroke.tool == PenTool.highlighter
? BrushKind.highlighter
: BrushKind.fountainPen,
);
/// Lossless adapter to the freezed/JSON [InkStroke] model. Null superset
/// fields fall back to [InkPoint]'s own defaults so the InkStroke round-trip
/// (fromInkStroke → toInkStroke) reproduces the original exactly.
InkStroke toInkStroke({DateTime? createdAt}) => InkStroke(
id: id,
points: points
.map(
(p) => InkPoint(
x: p.x,
y: p.y,
pressure: p.pressure ?? 0.5,
tilt: p.tilt ?? 0.0,
timestamp: p.timestamp ?? 0,
pointerDeviceKind:
p.pointerDeviceKind ?? InputDeviceKind.unknown,
),
)
.toList(),
tool: _toolToPenTool(tool),
color: color,
strokeWidth: width,
createdAt: createdAt ?? DateTime.fromMillisecondsSinceEpoch(0),
filled: filled,
textContent: textContent,
fontSize: fontSize,
);
static EditorTool _toolFromPenTool(PenTool tool) => switch (tool) {
PenTool.highlighter => EditorTool.highlighter,
PenTool.eraser => EditorTool.eraser,
_ => EditorTool.pen,
};
static PenTool _toolToPenTool(EditorTool tool) => switch (tool) {
EditorTool.pen => PenTool.pen,
EditorTool.highlighter => PenTool.highlighter,
EditorTool.eraser => PenTool.eraser,
};
}