Files
BadNote/lib/editor/canvas/pen_editor_screen.dart
Akiba So 1e2a83b0b9
All checks were successful
CI / Windows build (push) Successful in 10m45s
fix(canvas): compact page pill + pen diagnostic
Page slider is no longer persistent: a compact prev/'n/total'/next pill;
tapping the label reveals the slider (collapses again), so it stops
blocking the page. Add a pen-pressure diagnostic toggle (bug icon) that
shows the live kind/pressure/min/max Windows delivers — to pin down why
pressure reads flat on the Surface Pen.
2026-06-21 23:13:05 +08:00

512 lines
16 KiB
Dart

// lib/editor/canvas/pen_editor_screen.dart
//
// Page-based pen-first PDF editor. Opens a PDF with pdfrx's document API,
// shows ONE page at a time as a bitmap (PdfPageView — a per-page widget that
// renders to an image and does NOT capture pan/zoom gestures), overlaid by the
// ink layer. Both share one transform via PenCanvas. Prev/Next + jump-to-page.
import 'package:flutter/material.dart';
import 'package:pdfrx/pdfrx.dart';
import 'pen_canvas.dart';
import 'pen_stroke.dart';
class PenEditorScreen extends StatefulWidget {
const PenEditorScreen({super.key, required this.pdfPath});
final String pdfPath;
@override
State<PenEditorScreen> createState() => _PenEditorScreenState();
}
class _PenEditorScreenState extends State<PenEditorScreen> {
PdfDocument? _document;
Object? _openError;
/// 0-based current page index.
int _pageIndex = 0;
/// Strokes per page, keyed by 0-based page index (normalized coords).
final Map<int, List<PenStroke>> _strokesByPage = {};
/// One shared transform for the current page; recentred on page change so
/// each page opens fit-to-view and centered.
final TransformationController _transform = TransformationController();
/// Set when the page must be (re)centered on the next layout pass.
bool _needsCenter = true;
/// Live page value while dragging the page slider (null when not dragging).
double? _scrub;
/// Whether the page-jump slider is expanded (NOT persistent — toggled by
/// tapping the page label; collapses after a jump).
bool _showSlider = false;
/// Latest pen-event debug readout (kind/pressure/min/max) — shown only when
/// the diagnostic toggle is on, to inspect what Windows delivers.
String _penDebug = '';
bool _showPenDebug = false;
// Tool state.
CanvasTool _tool = CanvasTool.pen;
Color _color = Colors.black;
bool _allowFingerDrawing = false;
/// Pen width as a fraction of page width.
static const double _penWidthFraction = 0.004;
static const double _highlighterWidthFraction = 0.02;
static const List<Color> _palette = [
Colors.black,
Colors.red,
Colors.blue,
Colors.green,
Colors.orange,
];
@override
void initState() {
super.initState();
_open();
}
Future<void> _open() async {
try {
final doc = await PdfDocument.openFile(widget.pdfPath);
if (!mounted) {
doc.dispose();
return;
}
setState(() => _document = doc);
} catch (e) {
if (mounted) setState(() => _openError = e);
}
}
@override
void dispose() {
_document?.dispose();
_transform.dispose();
super.dispose();
}
List<PenStroke> get _currentStrokes =>
_strokesByPage.putIfAbsent(_pageIndex, () => <PenStroke>[]);
void _commitStroke(PenStroke stroke) {
setState(() {
// Replace with a NEW list so StaticInkPainter sees a fresh identity and
// actually repaints (mutating in place would alias the old painter's list
// and shouldRepaint would see no change → committed strokes vanish).
_strokesByPage[_pageIndex] = [
...?_strokesByPage[_pageIndex],
stroke,
];
});
}
void _eraseStroke(int index) {
setState(() {
final list = _strokesByPage[_pageIndex];
if (list != null && index >= 0 && index < list.length) {
final next = List<PenStroke>.of(list)..removeAt(index);
_strokesByPage[_pageIndex] = next;
}
});
}
void _goToPage(int index) {
final doc = _document;
if (doc == null) return;
final clamped = index.clamp(0, doc.pages.length - 1);
if (clamped == _pageIndex) return;
setState(() {
_pageIndex = clamped;
_needsCenter = true; // recenter the new page on next layout
});
}
/// Centre [pageSize] within [viewport] via the shared transform.
void _centerPage(Size viewport, Size pageSize) {
final tx = (viewport.width - pageSize.width) / 2;
final ty = (viewport.height - pageSize.height) / 2;
_transform.value = Matrix4.identity()..setTranslationRaw(tx, ty, 0);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Positioned.fill(child: _buildBody()),
// Floating Material You tool palette (top-center).
SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.only(top: 8),
child: _buildToolPalette(),
),
),
),
// Floating page-control pill (bottom-center).
if (_document != null)
SafeArea(
child: Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 16),
child: _buildPagePill(),
),
),
),
// Back button (top-left).
SafeArea(
child: Padding(
padding: const EdgeInsets.all(8),
child: _RoundIconButton(
icon: Icons.arrow_back,
tooltip: 'Back',
onPressed: () => Navigator.of(context).maybePop(),
),
),
),
// Pen diagnostic readout (top-right) — shows what Windows delivers.
if (_showPenDebug)
SafeArea(
child: Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.all(8),
child: Material(
color: Theme.of(context).colorScheme.inverseSurface,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 6),
child: Text(
_penDebug.isEmpty
? 'hover / draw with the pen…'
: _penDebug,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 12,
color: Theme.of(context).colorScheme.onInverseSurface,
),
),
),
),
),
),
),
],
),
);
}
Widget _buildBody() {
if (_openError != null) {
return Center(child: Text('Failed to open PDF:\n$_openError'));
}
final doc = _document;
if (doc == null) {
return const Center(child: CircularProgressIndicator());
}
if (doc.pages.isEmpty) {
return const Center(child: Text('PDF has no pages.'));
}
final page = doc.pages[_pageIndex];
return LayoutBuilder(
builder: (context, constraints) {
// Fit the page rectangle into the available viewport at scale 1.0; the
// InteractiveViewer then zooms/pans from there. Ink normalized coords
// map onto this rectangle.
final fit = (constraints.maxWidth / page.width)
.clamp(0.0, double.infinity);
final fitH = constraints.maxHeight / page.height;
final scale = fit < fitH ? fit : fitH;
final pageSize = Size(page.width * scale, page.height * scale);
if (_needsCenter) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_centerPage(
Size(constraints.maxWidth, constraints.maxHeight), pageSize);
setState(() => _needsCenter = false);
});
}
return PenCanvas(
key: ValueKey(_pageIndex),
pageSize: pageSize,
strokes: _currentStrokes,
transformationController: _transform,
tool: _tool,
color: _color,
strokeWidth: _tool == CanvasTool.highlighter
? _highlighterWidthFraction
: _penWidthFraction,
allowFingerDrawing: _allowFingerDrawing,
onPenDebug: _showPenDebug
? (s) => setState(() => _penDebug = s)
: null,
onStrokeComplete: _commitStroke,
onEraseStroke: _eraseStroke,
pageWidget: PdfPageView(
document: doc,
pageNumber: _pageIndex + 1,
// Fill the SizedBox exactly so ink aligns to the page rect (no
// internal letterboxing offset).
pageSizeCallback: (biggest, page, rotation) => biggest,
decoration: const BoxDecoration(color: Colors.white),
backgroundColor: Colors.white,
),
);
},
);
}
/// Floating Material You tool palette: a tonal rounded surface holding the
/// tools, color dots, and finger-drawing toggle.
Widget _buildToolPalette() {
final cs = Theme.of(context).colorScheme;
return Material(
color: cs.surfaceContainerHigh,
elevation: 3,
borderRadius: BorderRadius.circular(28),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
_ToolButton(
icon: Icons.edit_outlined,
selected: _tool == CanvasTool.pen,
tooltip: 'Pen',
onPressed: () => setState(() => _tool = CanvasTool.pen),
),
_ToolButton(
icon: Icons.brush_outlined,
selected: _tool == CanvasTool.highlighter,
tooltip: 'Highlighter',
onPressed: () => setState(() => _tool = CanvasTool.highlighter),
),
_ToolButton(
icon: Icons.cleaning_services_outlined,
selected: _tool == CanvasTool.eraser,
tooltip: 'Eraser',
onPressed: () => setState(() => _tool = CanvasTool.eraser),
),
_Divider(cs: cs),
for (final c in _palette) _colorDot(c, cs),
_Divider(cs: cs),
_ToolButton(
icon: _allowFingerDrawing ? Icons.touch_app : Icons.do_not_touch,
selected: _allowFingerDrawing,
tooltip: _allowFingerDrawing
? 'Finger drawing ON'
: 'Finger drawing OFF (pen only)',
onPressed: () =>
setState(() => _allowFingerDrawing = !_allowFingerDrawing),
),
_ToolButton(
icon: Icons.bug_report_outlined,
selected: _showPenDebug,
tooltip: 'Pen pressure diagnostic',
onPressed: () => setState(() => _showPenDebug = !_showPenDebug),
),
],
),
),
);
}
Widget _colorDot(Color c, ColorScheme cs) {
final selected = _color == c;
return GestureDetector(
onTap: () => setState(() => _color = c),
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
width: 28,
height: 28,
margin: const EdgeInsets.symmetric(horizontal: 3),
decoration: BoxDecoration(
color: c,
shape: BoxShape.circle,
border: Border.all(
color: selected ? cs.primary : cs.outlineVariant,
width: selected ? 3 : 1.5,
),
),
),
);
}
/// Floating page control: a COMPACT pill (prev / "n / total" / next). Tapping
/// the label reveals a drag-slider — which is NOT persistent (collapses again
/// on tap) so it doesn't block the page. No keyboard input (Windows IME is
/// unreliable).
Widget _buildPagePill() {
final doc = _document!;
final cs = Theme.of(context).colorScheme;
final total = doc.pages.length;
final shown = (_scrub ?? (_pageIndex + 1).toDouble()).round();
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// Slider — shown only when expanded (not persistent).
if (_showSlider && total > 1)
Container(
margin: const EdgeInsets.only(bottom: 8),
constraints: const BoxConstraints(maxWidth: 420),
child: Material(
color: cs.surfaceContainerHigh,
elevation: 3,
borderRadius: BorderRadius.circular(28),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Slider(
min: 1,
max: total.toDouble(),
value: (_scrub ?? (_pageIndex + 1).toDouble())
.clamp(1, total.toDouble()),
label: '$shown',
divisions: total - 1,
onChanged: (v) => setState(() => _scrub = v),
onChangeEnd: (v) {
setState(() => _scrub = null);
_goToPage(v.round() - 1);
},
),
),
),
),
// Compact pill — always; fits content (no big frame).
Material(
color: cs.surfaceContainerHigh,
elevation: 3,
borderRadius: BorderRadius.circular(28),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
tooltip: 'Previous page',
icon: const Icon(Icons.chevron_left),
onPressed:
_pageIndex > 0 ? () => _goToPage(_pageIndex - 1) : null,
),
TextButton(
onPressed: total > 1
? () => setState(() => _showSlider = !_showSlider)
: null,
child: Text(
'$shown / $total',
style: TextStyle(
color: cs.onSurface,
fontWeight: FontWeight.w600,
),
),
),
IconButton(
tooltip: 'Next page',
icon: const Icon(Icons.chevron_right),
onPressed: _pageIndex < total - 1
? () => _goToPage(_pageIndex + 1)
: null,
),
],
),
),
),
],
);
}
}
/// A Material You toggle-style icon button for the tool palette.
class _ToolButton extends StatelessWidget {
const _ToolButton({
required this.icon,
required this.selected,
required this.tooltip,
required this.onPressed,
});
final IconData icon;
final bool selected;
final String tooltip;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Tooltip(
message: tooltip,
child: InkWell(
borderRadius: BorderRadius.circular(20),
onTap: onPressed,
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
margin: const EdgeInsets.symmetric(horizontal: 2),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: selected ? cs.secondaryContainer : Colors.transparent,
borderRadius: BorderRadius.circular(20),
),
child: Icon(
icon,
size: 22,
color: selected ? cs.onSecondaryContainer : cs.onSurfaceVariant,
),
),
),
);
}
}
class _Divider extends StatelessWidget {
const _Divider({required this.cs});
final ColorScheme cs;
@override
Widget build(BuildContext context) => Container(
width: 1,
height: 24,
margin: const EdgeInsets.symmetric(horizontal: 6),
color: cs.outlineVariant,
);
}
/// A round, tonal icon button (used for the floating back button).
class _RoundIconButton extends StatelessWidget {
const _RoundIconButton({
required this.icon,
required this.tooltip,
required this.onPressed,
});
final IconData icon;
final String tooltip;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Material(
color: cs.surfaceContainerHigh,
elevation: 3,
shape: const CircleBorder(),
child: IconButton(
tooltip: tooltip,
icon: Icon(icon),
color: cs.onSurfaceVariant,
onPressed: onPressed,
),
);
}
}