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

@@ -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,
),
),
),