feat(pen): pressure-responsive width, configurable thinning, native Windows pen (tilt/buttons)
All checks were successful
CI / Windows build (push) Successful in 11m34s

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>
This commit is contained in:
2026-06-22 02:10:05 +08:00
parent e4a94d00c0
commit 3295018ee3
22 changed files with 1280 additions and 93 deletions

View File

@@ -7,13 +7,21 @@
import 'package:flutter/material.dart';
import 'package:perfect_freehand/perfect_freehand.dart' as pf;
import '../engine/stroke_geometry.dart' show kDefaultPenThinning;
import 'pen_stroke.dart';
/// Builds a filled outline [Path] for one stroke (already scaled to pixels).
///
/// [pageSize] maps normalized coords to pixels. [isComplete] should be false
/// for the in-progress live stroke so freehand tapers correctly.
Path buildStrokePath(PenStroke stroke, Size pageSize, {required bool isComplete}) {
/// for the in-progress live stroke so freehand tapers correctly. [thinning] is
/// the pressure→width response (shared default [kDefaultPenThinning]); the
/// SAME value drives the export path so screen and PDF never diverge.
Path buildStrokePath(
PenStroke stroke,
Size pageSize, {
required bool isComplete,
double thinning = kDefaultPenThinning,
}) {
final pixelWidth = stroke.width * pageSize.width;
final hasRealPressure = stroke.points.any((p) => p.pressure != null);
@@ -21,7 +29,7 @@ Path buildStrokePath(PenStroke stroke, Size pageSize, {required bool isComplete}
final pfPoints = stroke.points
.map(
(p) => pf.Point(
(p) => pf.PointVector(
p.x * pageSize.width,
p.y * pageSize.height,
p.pressure ?? 0.5,
@@ -31,23 +39,27 @@ Path buildStrokePath(PenStroke stroke, Size pageSize, {required bool isComplete}
final outline = pf.getStroke(
pfPoints,
size: pixelWidth,
// Highlighter keeps a constant width (no thinning); pen thins like the
// existing ink_canvas (_drawFreehand uses 0.7).
thinning: isHighlighter ? 0.0 : 0.7,
smoothing: 0.5,
streamline: 0.5,
// Real stylus pressure → don't simulate; no pressure → let freehand fake
// it based on velocity (matches ink_canvas behavior).
simulatePressure: !hasRealPressure && !isHighlighter,
isComplete: isComplete,
options: pf.StrokeOptions(
size: pixelWidth,
// Highlighter keeps a constant width (no thinning); pen uses the
// configurable [thinning] so real Surface-Pen pressure changes width.
thinning: isHighlighter ? 0.0 : thinning,
smoothing: 0.5,
streamline: 0.5,
// Real stylus pressure → don't simulate; no pressure → let freehand fake
// it based on velocity. (perfect_freehand 2.x honors REAL pressure when
// simulatePressure is false — 1.0.4 ignored it, which made width
// unresponsive to pen force.)
simulatePressure: !hasRealPressure && !isHighlighter,
isComplete: isComplete,
),
);
final path = Path();
if (outline.isEmpty) return path;
path.moveTo(outline.first.x, outline.first.y);
path.moveTo(outline.first.dx, outline.first.dy);
for (var i = 1; i < outline.length; i++) {
path.lineTo(outline[i].x, outline[i].y);
path.lineTo(outline[i].dx, outline[i].dy);
}
path.close();
return path;
@@ -56,15 +68,23 @@ Path buildStrokePath(PenStroke stroke, Size pageSize, {required bool isComplete}
/// Paints all committed strokes for the page. Repaints only when the stroke
/// list identity or page size changes (kept behind a RepaintBoundary).
class StaticInkPainter extends CustomPainter {
StaticInkPainter({required this.strokes, required this.pageSize});
StaticInkPainter({
required this.strokes,
required this.pageSize,
this.thinning = kDefaultPenThinning,
});
final List<PenStroke> strokes;
final Size pageSize;
/// Pressure→width response shared with the live/export paths.
final double thinning;
@override
void paint(Canvas canvas, Size size) {
for (final stroke in strokes) {
final path = buildStrokePath(stroke, pageSize, isComplete: true);
final path =
buildStrokePath(stroke, pageSize, isComplete: true, thinning: thinning);
if (path.getBounds().isEmpty) continue;
canvas.drawPath(
path,
@@ -80,23 +100,32 @@ class StaticInkPainter extends CustomPainter {
bool shouldRepaint(StaticInkPainter old) =>
!identical(old.strokes, strokes) ||
old.strokes.length != strokes.length ||
old.pageSize != pageSize;
old.pageSize != pageSize ||
old.thinning != thinning;
}
/// Paints just the in-progress stroke (the live layer), kept behind its own
/// RepaintBoundary so committed strokes don't repaint on every move.
class LiveInkPainter extends CustomPainter {
LiveInkPainter({required this.stroke, required this.pageSize});
LiveInkPainter({
required this.stroke,
required this.pageSize,
this.thinning = kDefaultPenThinning,
});
/// Current in-progress stroke, or null when nothing is being drawn.
final PenStroke? stroke;
final Size pageSize;
/// Pressure→width response shared with the static/export paths.
final double thinning;
@override
void paint(Canvas canvas, Size size) {
final s = stroke;
if (s == null || s.points.isEmpty) return;
final path = buildStrokePath(s, pageSize, isComplete: false);
final path =
buildStrokePath(s, pageSize, isComplete: false, thinning: thinning);
if (path.getBounds().isEmpty) return;
canvas.drawPath(
path,
@@ -109,5 +138,7 @@ class LiveInkPainter extends CustomPainter {
@override
bool shouldRepaint(LiveInkPainter old) =>
!identical(old.stroke, stroke) || old.pageSize != pageSize;
!identical(old.stroke, stroke) ||
old.pageSize != pageSize ||
old.thinning != thinning;
}

View File

@@ -21,6 +21,9 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../engine/stroke_geometry.dart' show kDefaultPenThinning;
import '../input/pen_config.dart';
import '../input/pen_input_service.dart';
import 'ink_painters.dart';
import 'pen_stroke.dart';
@@ -43,6 +46,10 @@ class PenCanvas extends StatefulWidget {
this.minScale = 0.5,
this.maxScale = 8.0,
this.onPenDebug,
this.thinning = kDefaultPenThinning,
this.sideButtonAction = PenButtonAction.eraser,
this.eraserEndAction = PenButtonAction.eraser,
this.onPenButtonAction,
});
/// Debug hook: called with a readout of the latest pen event
@@ -82,6 +89,20 @@ class PenCanvas extends StatefulWidget {
final double minScale;
final double maxScale;
/// perfect_freehand pressure→width response, from `PenConfig.pressureSensitivity`.
final double thinning;
/// Configured action for the pen's side barrel button (W3 — resolved against
/// the native pen plugin's flags on Windows).
final PenButtonAction sideButtonAction;
/// Configured action for the pen's eraser/inverted end (W3).
final PenButtonAction eraserEndAction;
/// Fired (edge-triggered) when a hardware pen button mapped to a non-eraser
/// action (undo / toggleTool) is pressed.
final void Function(PenButtonAction action)? onPenButtonAction;
@override
State<PenCanvas> createState() => _PenCanvasState();
}
@@ -130,15 +151,79 @@ class _PenCanvasState extends State<PenCanvas> {
return null;
}
/// The eraser signal: barrel/secondary button held, or an inverted stylus.
bool _isEraserSignal(PointerEvent event) =>
event.buttons == kSecondaryButton ||
event.kind == PointerDeviceKind.invertedStylus;
/// The eraser signal. Two sources, ORed:
/// 1. Flutter-native: secondary button held or an inverted stylus (works on
/// desktop / platforms that surface these).
/// 2. Windows native pen plugin: barrel / inverted / eraser flags that
/// Flutter 3.44 drops, mapped through the configured side-button /
/// eraser-end actions (W3). Level-triggered, so holding the button keeps
/// erasing — correct for an eraser.
bool _isEraserSignal(PointerEvent event) {
if (event.buttons == kSecondaryButton ||
event.kind == PointerDeviceKind.invertedStylus) {
return true;
}
final hw = PenInputService.instance;
if (hw.isActive) {
final s = hw.current;
if ((s.inverted || s.eraser) &&
widget.eraserEndAction == PenButtonAction.eraser) {
return true;
}
if (s.barrel && widget.sideButtonAction == PenButtonAction.eraser) {
return true;
}
}
return false;
}
/// Resolve the currently-active configured action from the native pen flags
/// (eraser-end takes precedence over the side button when both are set).
PenButtonAction _activeHwAction() {
final hw = PenInputService.instance;
if (!hw.isActive) return PenButtonAction.none;
final s = hw.current;
if (s.inverted || s.eraser) return widget.eraserEndAction;
if (s.barrel) return widget.sideButtonAction;
return PenButtonAction.none;
}
/// Last hardware action seen, for rising-edge detection of undo/toggleTool.
PenButtonAction _lastHwAction = PenButtonAction.none;
/// Edge-triggered dispatch of non-eraser button actions (undo / toggleTool).
/// Eraser is handled level-triggered by [_isEraserSignal]; pan suppresses
/// drawing via [_shouldDraw].
void _dispatchHwButtonActions() {
final action = _activeHwAction();
if (action == _lastHwAction) return;
_lastHwAction = action;
if (action == PenButtonAction.undo ||
action == PenButtonAction.toggleTool) {
widget.onPenButtonAction?.call(action);
}
}
/// True while a hardware button mapped to `pan` is held (suppresses drawing
/// so the InteractiveViewer pans instead).
bool get _hwPanActive => _activeHwAction() == PenButtonAction.pan;
/// Pen tilt magnitude (degrees) for a stylus event, or null when unavailable.
double? _tiltFor(PointerEvent event) {
if (!_isStylus(event.kind)) return null;
final hw = PenInputService.instance;
if (!hw.isActive) return null;
final t = hw.current.tiltMagnitude;
return t == 0 ? null : t;
}
/// Decide whether the gesture currently forming should DRAW.
/// True iff exactly one active pointer AND (stylus OR finger-drawing on).
bool _shouldDraw(PointerDeviceKind kind) {
if (_activePointers.length != 1) return false;
// A hardware pen button mapped to `pan` suppresses drawing so the
// InteractiveViewer pans instead.
if (_hwPanActive) return false;
if (_isStylus(kind)) return true;
if (kind == PointerDeviceKind.mouse) return true;
if (kind == PointerDeviceKind.touch) return _fingerDrawingEnabled;
@@ -149,7 +234,8 @@ class _PenCanvasState extends State<PenCanvas> {
/// Map a global pointer position into normalized page coords using the
/// shared transform (inverse) and this widget's geometry.
PenPoint? _toNormalized(Offset globalPosition, double? pressure) {
PenPoint? _toNormalized(Offset globalPosition, double? pressure,
{double? tilt}) {
final box = context.findRenderObject() as RenderBox?;
if (box == null) return null;
final local = box.globalToLocal(globalPosition);
@@ -159,7 +245,7 @@ class _PenCanvasState extends State<PenCanvas> {
final nx = scene.dx / widget.pageSize.width;
final ny = scene.dy / widget.pageSize.height;
return PenPoint(nx, ny, pressure);
return PenPoint(nx, ny, pressure, tilt: tilt);
}
// --- Stroke lifecycle -----------------------------------------------------
@@ -167,7 +253,8 @@ class _PenCanvasState extends State<PenCanvas> {
void _startStroke(PointerDownEvent event) {
_drawPointer = event.pointer;
_livePoints.clear();
final p = _toNormalized(event.position, _normalizedPressure(event));
final p = _toNormalized(event.position, _normalizedPressure(event),
tilt: _tiltFor(event));
if (p != null) _livePoints.add(p);
if (_eraserActive || widget.tool == CanvasTool.eraser) {
@@ -180,7 +267,8 @@ class _PenCanvasState extends State<PenCanvas> {
}
void _extendStroke(PointerMoveEvent event) {
final p = _toNormalized(event.position, _normalizedPressure(event));
final p = _toNormalized(event.position, _normalizedPressure(event),
tilt: _tiltFor(event));
if (p == null) return;
if (_eraserActive || widget.tool == CanvasTool.eraser) {
@@ -255,18 +343,28 @@ class _PenCanvasState extends State<PenCanvas> {
// --- Listener callbacks ---------------------------------------------------
/// Highest NORMALIZED pressure seen since the diagnostic was last reset —
/// makes "does pressure actually vary?" unambiguous on the readout.
double _peakNorm = 0;
void _emitPenDebug(PointerEvent event) {
final cb = widget.onPenDebug;
if (cb == null) return;
cb('${event.kind.name} p=${event.pressure.toStringAsFixed(3)} '
'min=${event.pressureMin.toStringAsFixed(2)} '
'max=${event.pressureMax.toStringAsFixed(2)} '
'tilt=${event.tilt.toStringAsFixed(2)}');
final norm = _normalizedPressure(event);
if (norm != null && norm > _peakNorm) _peakNorm = norm;
cb('${event.kind.name} raw=${event.pressure.toStringAsFixed(1)}'
'/${event.pressureMax.toStringAsFixed(0)} '
'norm=${norm?.toStringAsFixed(3) ?? "null"} '
'peak=${_peakNorm.toStringAsFixed(3)} '
'btn=${event.buttons} tilt=${event.tilt.toStringAsFixed(2)}');
}
void _onPointerHover(PointerHoverEvent event) {
if (_isStylus(event.kind)) {
_emitPenDebug(event);
// Fire edge-triggered button actions (undo / toggleTool) on hover so a
// mapped barrel press works without first touching down.
_dispatchHwButtonActions();
// Detect eraser (barrel button / inverted) while hovering.
_eraserActive = _isEraserSignal(event);
}
@@ -274,7 +372,13 @@ class _PenCanvasState extends State<PenCanvas> {
void _onPointerDown(PointerDownEvent event) {
if (event.kind == PointerDeviceKind.trackpad) return;
if (_isStylus(event.kind)) _emitPenDebug(event);
if (_isStylus(event.kind)) {
_emitPenDebug(event);
// Fire edge-triggered button actions for a direct pen-down (no prior
// hover); the native observer latched this contact's flags before Flutter
// synthesized this event (plan M1/M2).
_dispatchHwButtonActions();
}
_activePointers[event.pointer] = event.kind;
@@ -343,8 +447,15 @@ class _PenCanvasState extends State<PenCanvas> {
height: widget.pageSize.height,
child: Stack(
children: [
// PDF page bitmap.
Positioned.fill(child: widget.pageWidget),
// PDF page bitmap. Wrapped in its own RepaintBoundary (W2) so the
// per-move live-ink repaints and the static-ink repaints never
// mark the page's raster layer dirty — isolating it from
// ink-driven repaints. (The definitive crisp-on-zoom / no-flash
// fix is the P0.5 page_tile DPI-on-settle double-buffer; this
// boundary is the safe, non-regressive interim per plan M3.)
Positioned.fill(
child: RepaintBoundary(child: widget.pageWidget),
),
// Committed ink (static layer, isolated repaint).
Positioned.fill(
child: RepaintBoundary(
@@ -352,6 +463,7 @@ class _PenCanvasState extends State<PenCanvas> {
painter: StaticInkPainter(
strokes: widget.strokes,
pageSize: widget.pageSize,
thinning: widget.thinning,
),
),
),
@@ -363,6 +475,7 @@ class _PenCanvasState extends State<PenCanvas> {
painter: LiveInkPainter(
stroke: _liveStroke,
pageSize: widget.pageSize,
thinning: widget.thinning,
),
),
),

View File

@@ -9,9 +9,11 @@ import 'package:flutter/material.dart';
import 'package:pdfrx/pdfrx.dart';
import '../../services/database_service.dart';
import '../engine/stroke_geometry.dart' show kDefaultPenThinning;
import '../engine/stroke_model.dart';
import '../engine/undo_stack.dart';
import '../input/pen_config.dart';
import '../input/pen_input_service.dart';
import '../persistence/editor_repository.dart';
import '../persistence/save_scheduler.dart';
import '../ui/pen_settings_page.dart';
@@ -98,8 +100,8 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
Color _color = Colors.black;
bool _allowFingerDrawing = false;
/// Pen width as a fraction of page width.
static const double _penWidthFraction = 0.004;
/// Pen width as a fraction of page width (base; pressure thins it down).
static const double _penWidthFraction = 0.006;
static const double _highlighterWidthFraction = 0.02;
static const List<Color> _palette = [
@@ -114,6 +116,9 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
void initState() {
super.initState();
_documentId = _documentIdFromPath(widget.pdfPath);
// Begin listening to the native Windows pen plugin (barrel/eraser/tilt).
// No-op on platforms without the plugin (W3).
PenInputService.instance.start();
_initPersistence();
_initPenConfig();
_open();
@@ -125,6 +130,9 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
controller.dispose();
return;
}
// Rebuild the editor when pen settings change (width, pressure
// sensitivity, button mappings) so the live canvas reflects them.
controller.addListener(_onPenConfigChanged);
setState(() {
_penConfig = controller;
// Adopt the persisted finger-drawing preference as the initial local
@@ -134,6 +142,10 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
});
}
void _onPenConfigChanged() {
if (mounted) setState(() {});
}
Future<void> _initPersistence() async {
final service = await DatabaseService.getInstance();
if (!mounted) return;
@@ -159,7 +171,7 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
loaded[pageIndex] = entry.value
.map((es) => PenStroke(
points: es.points
.map((ep) => PenPoint(ep.x, ep.y, ep.pressure))
.map((ep) => PenPoint(ep.x, ep.y, ep.pressure, tilt: ep.tilt))
.toList(),
color: es.color,
width: es.width,
@@ -211,6 +223,7 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
_document?.dispose();
_transform.dispose();
_penConfig?.dispose();
PenInputService.instance.stop();
super.dispose();
}
@@ -308,6 +321,33 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
_schedulePageSave(_pageIndex, List<PenStroke>.of(snapshot));
}
/// Cycle pen → highlighter → eraser → pen (for the toggleTool button action).
void _cycleTool() {
setState(() {
_tool = switch (_tool) {
CanvasTool.pen => CanvasTool.highlighter,
CanvasTool.highlighter => CanvasTool.eraser,
CanvasTool.eraser => CanvasTool.pen,
};
});
}
/// Handle a hardware pen-button action delivered by [PenCanvas] (W3).
/// `eraser` and `pan` are handled inside the canvas; here we map the
/// edge-triggered ones.
void _handlePenButtonAction(PenButtonAction action) {
switch (action) {
case PenButtonAction.undo:
_performUndo();
case PenButtonAction.toggleTool:
_cycleTool();
case PenButtonAction.eraser:
case PenButtonAction.pan:
case PenButtonAction.none:
break;
}
}
/// Toggle finger-drawing, keeping the local state and the persisted config
/// (when loaded) in sync.
void _toggleFingerDrawing() {
@@ -457,6 +497,13 @@ class _PenEditorScreenState extends State<PenEditorScreen> {
? (_penConfig?.value.highlighterWidth ??
_highlighterWidthFraction)
: (_penConfig?.value.penWidth ?? _penWidthFraction),
thinning:
_penConfig?.value.pressureSensitivity ?? kDefaultPenThinning,
sideButtonAction:
_penConfig?.value.sideButton ?? PenButtonAction.eraser,
eraserEndAction:
_penConfig?.value.eraserEnd ?? PenButtonAction.eraser,
onPenButtonAction: _handlePenButtonAction,
allowFingerDrawing: _allowFingerDrawing,
onPenDebug: _showPenDebug
? (s) => setState(() => _penDebug = s)

View File

@@ -11,13 +11,17 @@ import 'package:flutter/foundation.dart';
/// [x]/[y] are normalized to the page rectangle ([0,1]).
/// [pressure] is the normalized stylus pressure ([0,1]) or null when the
/// device reported no usable pressure (perfect_freehand then simulates it).
/// [tilt] is the pen tilt magnitude in degrees (0 = perpendicular), or null
/// when unavailable. On Windows it is sourced from the native pen plugin
/// (`badnote/pen`) since Flutter 3.44 does not surface tilt itself.
@immutable
class PenPoint {
const PenPoint(this.x, this.y, this.pressure);
const PenPoint(this.x, this.y, this.pressure, {this.tilt});
final double x;
final double y;
final double? pressure;
final double? tilt;
}
/// Which kind of mark a stroke is.