feat(pen): pressure-responsive width, configurable thinning, native Windows pen (tilt/buttons)
All checks were successful
CI / Windows build (push) Successful in 11m34s
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:
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -13,18 +13,30 @@ import 'package:perfect_freehand/perfect_freehand.dart' as pf;
|
||||
|
||||
import 'stroke_model.dart';
|
||||
|
||||
/// Canonical default for perfect_freehand's `thinning` (how strongly pressure
|
||||
/// modulates stroke width). The SINGLE source of truth shared by the on-screen
|
||||
/// painter ([buildStrokeOutline] here and `ink_painters.buildStrokePath`) and
|
||||
/// the PDF export path, so screen and export can never diverge. `0.85` =
|
||||
/// pressure visibly sweeps width; preserves the existing feel + export golden.
|
||||
/// Overridable per-stroke via [PenConfig.pressureSensitivity].
|
||||
const double kDefaultPenThinning = 0.85;
|
||||
|
||||
/// Builds a closed, fillable outline [Path] for one [stroke], scaled into the
|
||||
/// pixel space of [pageSize] (which maps normalized [0,1] coords to pixels).
|
||||
///
|
||||
/// [isComplete] should be false for the in-progress live stroke so freehand
|
||||
/// tapers the trailing end correctly, and true for committed strokes.
|
||||
///
|
||||
/// [thinning] is perfect_freehand's pressure→width response (see
|
||||
/// [kDefaultPenThinning]); highlighter always forces `0.0` (constant width).
|
||||
///
|
||||
/// Returns an empty [Path] when the stroke has no points (or freehand produces
|
||||
/// no outline).
|
||||
Path buildStrokeOutline(
|
||||
EditorStroke stroke,
|
||||
Size pageSize, {
|
||||
required bool isComplete,
|
||||
double thinning = kDefaultPenThinning,
|
||||
}) {
|
||||
final path = Path();
|
||||
if (stroke.points.isEmpty) return path;
|
||||
@@ -36,7 +48,7 @@ Path buildStrokeOutline(
|
||||
|
||||
final pfPoints = stroke.points
|
||||
.map(
|
||||
(p) => pf.Point(
|
||||
(p) => pf.PointVector(
|
||||
p.x * pageSize.width,
|
||||
p.y * pageSize.height,
|
||||
p.pressure ?? 0.5,
|
||||
@@ -46,22 +58,25 @@ Path buildStrokeOutline(
|
||||
|
||||
final outline = pf.getStroke(
|
||||
pfPoints,
|
||||
size: pixelWidth,
|
||||
// Highlighter keeps a constant width (no thinning); pen thins (0.7),
|
||||
// matching the live recipe.
|
||||
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 (highlighter never simulates).
|
||||
simulatePressure: !hasRealPressure && !isHighlighter,
|
||||
isComplete: isComplete,
|
||||
options: pf.StrokeOptions(
|
||||
size: pixelWidth,
|
||||
// Highlighter keeps a constant width (no thinning); pen uses the
|
||||
// configurable [thinning] so 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 (highlighter never simulates). perfect_freehand
|
||||
// 2.x honors real pressure when simulatePressure is false.
|
||||
simulatePressure: !hasRealPressure && !isHighlighter,
|
||||
isComplete: isComplete,
|
||||
),
|
||||
);
|
||||
|
||||
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;
|
||||
|
||||
@@ -103,12 +103,14 @@ abstract class EditorStroke with _$EditorStroke {
|
||||
|
||||
// ---- Adapters -----------------------------------------------------------
|
||||
|
||||
/// Adapts an in-memory live [PenStroke] (normalized, no tilt/timestamp/kind).
|
||||
/// 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
|
||||
.map((p) => EditorPoint(x: p.x, y: p.y, pressure: p.pressure))
|
||||
.map((p) =>
|
||||
EditorPoint(x: p.x, y: p.y, pressure: p.pressure, tilt: p.tilt))
|
||||
.toList(),
|
||||
tool: switch (stroke.kind) {
|
||||
PenStrokeKind.pen => EditorTool.pen,
|
||||
|
||||
@@ -4,6 +4,8 @@ import 'dart:math';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../engine/stroke_geometry.dart' show kDefaultPenThinning;
|
||||
|
||||
/// Action that can be triggered by a hardware pen button or the eraser end.
|
||||
enum PenButtonAction {
|
||||
none,
|
||||
@@ -25,10 +27,13 @@ class PenConfig {
|
||||
this.fingerDrawing = false,
|
||||
this.penWidth = 0.004,
|
||||
this.highlighterWidth = 0.02,
|
||||
this.pressureSensitivity = kDefaultPenThinning,
|
||||
}) : assert(pressureGamma >= 0.3 && pressureGamma <= 3.0,
|
||||
'pressureGamma must be in [0.3, 3.0]'),
|
||||
assert(palmRejectionMs >= 0.0 && palmRejectionMs <= 500.0,
|
||||
'palmRejectionMs must be in [0, 500]');
|
||||
'palmRejectionMs must be in [0, 500]'),
|
||||
assert(pressureSensitivity >= 0.0 && pressureSensitivity <= 1.0,
|
||||
'pressureSensitivity must be in [0, 1]');
|
||||
|
||||
/// Which action fires when the side barrel button is held.
|
||||
final PenButtonAction sideButton;
|
||||
@@ -54,6 +59,13 @@ class PenConfig {
|
||||
/// Highlighter stroke width as a fraction of the canvas width.
|
||||
final double highlighterWidth;
|
||||
|
||||
/// How strongly stylus pressure modulates stroke width — maps directly to
|
||||
/// perfect_freehand's `thinning`. Range [0,1]; `0` = constant width,
|
||||
/// higher = pressure sweeps width more (Saber's `StrokeOptions.thinning`
|
||||
/// model). Default [kDefaultPenThinning] so the out-of-box feel and the
|
||||
/// export golden are unchanged.
|
||||
final double pressureSensitivity;
|
||||
|
||||
PenConfig copyWith({
|
||||
PenButtonAction? sideButton,
|
||||
PenButtonAction? eraserEnd,
|
||||
@@ -62,6 +74,7 @@ class PenConfig {
|
||||
bool? fingerDrawing,
|
||||
double? penWidth,
|
||||
double? highlighterWidth,
|
||||
double? pressureSensitivity,
|
||||
}) {
|
||||
return PenConfig(
|
||||
sideButton: sideButton ?? this.sideButton,
|
||||
@@ -71,6 +84,7 @@ class PenConfig {
|
||||
fingerDrawing: fingerDrawing ?? this.fingerDrawing,
|
||||
penWidth: penWidth ?? this.penWidth,
|
||||
highlighterWidth: highlighterWidth ?? this.highlighterWidth,
|
||||
pressureSensitivity: pressureSensitivity ?? this.pressureSensitivity,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -82,6 +96,7 @@ class PenConfig {
|
||||
'fingerDrawing': fingerDrawing,
|
||||
'penWidth': penWidth,
|
||||
'highlighterWidth': highlighterWidth,
|
||||
'pressureSensitivity': pressureSensitivity,
|
||||
};
|
||||
|
||||
factory PenConfig.fromJson(Map<String, dynamic> json) {
|
||||
@@ -97,6 +112,8 @@ class PenConfig {
|
||||
fingerDrawing: json['fingerDrawing'] as bool? ?? false,
|
||||
penWidth: (json['penWidth'] as num?)?.toDouble() ?? 0.004,
|
||||
highlighterWidth: (json['highlighterWidth'] as num?)?.toDouble() ?? 0.02,
|
||||
pressureSensitivity:
|
||||
(json['pressureSensitivity'] as num?)?.toDouble() ?? kDefaultPenThinning,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -111,7 +128,8 @@ class PenConfig {
|
||||
palmRejectionMs == other.palmRejectionMs &&
|
||||
fingerDrawing == other.fingerDrawing &&
|
||||
penWidth == other.penWidth &&
|
||||
highlighterWidth == other.highlighterWidth;
|
||||
highlighterWidth == other.highlighterWidth &&
|
||||
pressureSensitivity == other.pressureSensitivity;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
@@ -122,6 +140,7 @@ class PenConfig {
|
||||
fingerDrawing,
|
||||
penWidth,
|
||||
highlighterWidth,
|
||||
pressureSensitivity,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -215,4 +234,11 @@ class PenConfigController extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
await _persist();
|
||||
}
|
||||
|
||||
/// Sets [PenConfig.pressureSensitivity]. Clamped to [0, 1].
|
||||
Future<void> setPressureSensitivity(double sensitivity) async {
|
||||
_value = _value.copyWith(pressureSensitivity: sensitivity.clamp(0.0, 1.0));
|
||||
notifyListeners();
|
||||
await _persist();
|
||||
}
|
||||
}
|
||||
|
||||
136
lib/editor/input/pen_input_service.dart
Normal file
136
lib/editor/input/pen_input_service.dart
Normal file
@@ -0,0 +1,136 @@
|
||||
// lib/editor/input/pen_input_service.dart
|
||||
//
|
||||
// Dart side of the native Windows pen observer (`windows/runner/pen_channel.cpp`).
|
||||
//
|
||||
// WHY THIS EXISTS: Flutter 3.44 on Windows delivers stylus PRESSURE but drops
|
||||
// the pen's barrel button, eraser/inverted end, and tilt (it does not map
|
||||
// POINTER_PEN_FLAG_* into `PointerEvent.buttons`/`invertedStylus`/`tilt`). The
|
||||
// native plugin observes WM_POINTER + GetPointerPenInfo and streams the missing
|
||||
// hardware state over an EventChannel; this service latches the LATEST value.
|
||||
//
|
||||
// CORRELATION (plan M2): we do NOT key state by Win32 pointerId joined to
|
||||
// Flutter's `event.pointer` — those are different id spaces. Only one pen is
|
||||
// active at a time, so a single latched "current" state is correct. The native
|
||||
// observer runs at the TOP of the window proc (BEFORE Flutter synthesizes its
|
||||
// pointer event, plan M1), so by the time Dart's pointer-down handler reads
|
||||
// [current], the latch already reflects that exact contact — no hover required.
|
||||
//
|
||||
// GRACEFUL DEGRADATION: on non-Windows (or if the channel is silent) the stream
|
||||
// simply never emits / errors are swallowed, and [current] stays [PenHardwareState.empty]
|
||||
// so the canvas falls back to its normal Flutter-pressure drawing.
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// Latest hardware pen state delivered by the native observer.
|
||||
class PenHardwareState {
|
||||
const PenHardwareState({
|
||||
this.barrel = false,
|
||||
this.inverted = false,
|
||||
this.eraser = false,
|
||||
this.tiltX = 0.0,
|
||||
this.tiltY = 0.0,
|
||||
});
|
||||
|
||||
/// Side barrel button held.
|
||||
final bool barrel;
|
||||
|
||||
/// Pen flipped to the inverted (eraser) end.
|
||||
final bool inverted;
|
||||
|
||||
/// Hardware eraser flag set.
|
||||
final bool eraser;
|
||||
|
||||
/// Tilt in degrees along X / Y ([-90, 90]); 0 = perpendicular.
|
||||
final double tiltX;
|
||||
final double tiltY;
|
||||
|
||||
/// Combined tilt magnitude in degrees (for [PenPoint.tilt]).
|
||||
double get tiltMagnitude {
|
||||
final t = tiltX * tiltX + tiltY * tiltY;
|
||||
return t <= 0 ? 0.0 : _sqrt(t);
|
||||
}
|
||||
|
||||
static const empty = PenHardwareState();
|
||||
}
|
||||
|
||||
// Avoids importing dart:math for a single call.
|
||||
double _sqrt(double v) {
|
||||
if (v <= 0) return 0;
|
||||
var x = v;
|
||||
var last = 0.0;
|
||||
// Newton's method; converges fast for the small (<=~127) magnitudes here.
|
||||
for (var i = 0; i < 12 && x != last; i++) {
|
||||
last = x;
|
||||
x = 0.5 * (x + v / x);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
/// Latches the most recent [PenHardwareState] streamed by the native pen plugin.
|
||||
///
|
||||
/// Use the singleton [PenInputService.instance]. Call [start] once (e.g. in the
|
||||
/// editor's `initState`) and [stop] on dispose.
|
||||
class PenInputService {
|
||||
PenInputService._();
|
||||
|
||||
/// Process-wide singleton (one physical pen).
|
||||
static final PenInputService instance = PenInputService._();
|
||||
|
||||
/// Must match the native `EventChannel` name in `pen_channel.cpp`.
|
||||
static const EventChannel _channel = EventChannel('badnote/pen');
|
||||
|
||||
StreamSubscription<dynamic>? _sub;
|
||||
PenHardwareState _current = PenHardwareState.empty;
|
||||
|
||||
/// The latest hardware pen state (or [PenHardwareState.empty] when no native
|
||||
/// data has arrived — non-Windows, plugin absent, or channel silent).
|
||||
PenHardwareState get current => _current;
|
||||
|
||||
/// Whether the native channel has delivered at least one event (i.e. the
|
||||
/// native pen plugin is present and active). Used to prefer hardware signals
|
||||
/// over the Flutter fallback only when they are actually available.
|
||||
bool get isActive => _active;
|
||||
bool _active = false;
|
||||
|
||||
/// Begins listening to the native channel. Idempotent; safe on any platform
|
||||
/// (no-ops where the channel has no handler).
|
||||
void start() {
|
||||
if (_sub != null) return;
|
||||
try {
|
||||
_sub = _channel.receiveBroadcastStream().listen(
|
||||
_onEvent,
|
||||
onError: (Object _) {
|
||||
// No native handler (e.g. Linux/macOS) or transient error — ignore
|
||||
// and keep the empty fallback state.
|
||||
},
|
||||
cancelOnError: false,
|
||||
);
|
||||
} catch (_) {
|
||||
// receiveBroadcastStream can throw synchronously if the platform side is
|
||||
// unavailable; degrade silently.
|
||||
}
|
||||
}
|
||||
|
||||
void _onEvent(dynamic event) {
|
||||
if (event is! Map) return;
|
||||
final flags = (event['flags'] as num?)?.toInt() ?? 0;
|
||||
_current = PenHardwareState(
|
||||
barrel: flags & 0x1 != 0,
|
||||
inverted: flags & 0x2 != 0,
|
||||
eraser: flags & 0x4 != 0,
|
||||
tiltX: (event['tiltX'] as num?)?.toDouble() ?? 0.0,
|
||||
tiltY: (event['tiltY'] as num?)?.toDouble() ?? 0.0,
|
||||
);
|
||||
_active = true;
|
||||
}
|
||||
|
||||
/// Stops listening and resets state.
|
||||
void stop() {
|
||||
_sub?.cancel();
|
||||
_sub = null;
|
||||
_active = false;
|
||||
_current = PenHardwareState.empty;
|
||||
}
|
||||
}
|
||||
@@ -93,6 +93,15 @@ class _PenSettingsSheet extends StatelessWidget {
|
||||
icon: Icons.compress,
|
||||
colorScheme: colorScheme,
|
||||
),
|
||||
_SliderTile(
|
||||
label: 'Pressure Sensitivity',
|
||||
value: config.pressureSensitivity,
|
||||
min: 0.0,
|
||||
max: 1.0,
|
||||
divisions: 20,
|
||||
formatValue: (v) => v.toStringAsFixed(2),
|
||||
onChanged: controller.setPressureSensitivity,
|
||||
),
|
||||
_SliderTile(
|
||||
label: 'Pressure Gamma',
|
||||
value: config.pressureGamma,
|
||||
|
||||
Reference in New Issue
Block a user