Files
BadNote/lib/services/pdf_service.dart
Akiba So 3295018ee3
All checks were successful
CI / Windows build (push) Successful in 11m34s
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

330 lines
11 KiB
Dart

import 'dart:io';
import 'dart:math' as math;
import 'dart:ui';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:perfect_freehand/perfect_freehand.dart' as pf;
import 'package:syncfusion_flutter_pdf/pdf.dart';
import '../models/ink_stroke.dart';
import '../models/pen_tool.dart';
/// Service for PDF operations: file picking, info extraction, and annotation export.
class PdfService {
/// Pick a PDF file path using the cross-platform file_picker.
Future<String?> pickPdfFile() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
final files = result?.files;
if (files == null || files.isEmpty) return null;
return files.first.path;
}
/// Get the page count of the PDF at [filePath].
Future<int> getPageCount(String filePath) async {
final bytes = await File(filePath).readAsBytes();
final document = PdfDocument(inputBytes: bytes);
try {
return document.pages.count;
} finally {
document.dispose();
}
}
/// Get basic info about a PDF file: fileName and fileSize.
Future<Map<String, dynamic>> getPdfInfo(String filePath) async {
final file = File(filePath);
final fileSize = await file.length();
return {'fileName': p.basename(filePath), 'fileSize': fileSize};
}
/// Export an annotated PDF by drawing ink strokes onto each page.
///
/// [annotations] maps page index (0-based) to lists of [InkStroke].
/// Stroke coordinates are normalized to [0, 1] relative to the annotation
/// overlay size used during capture, and are scaled to actual PDF page
/// dimensions during export.
///
/// Returns the path to the exported annotated PDF.
Future<String> exportAnnotatedPdf(
String filePath,
Map<int, List<InkStroke>> annotations,
) async {
final bytes = await File(filePath).readAsBytes();
final document = PdfDocument(inputBytes: bytes);
try {
for (final entry in annotations.entries) {
final pageIndex = entry.key;
final strokes = entry.value;
if (strokes.isEmpty) continue;
if (pageIndex >= document.pages.count) continue;
final page = document.pages[pageIndex];
_renderStrokes(page, strokes);
}
final outputDir = await getTemporaryDirectory();
final baseName = p.basenameWithoutExtension(filePath);
final outputPath = p.join(outputDir.path, '${baseName}_annotated.pdf');
final savedBytes = await document.save();
await File(outputPath).writeAsBytes(savedBytes, flush: true);
return outputPath;
} finally {
document.dispose();
}
}
/// Delete a page at [pageIndex]. Returns true on success.
Future<bool> deletePage(String filePath, int pageIndex) async {
try {
final bytes = await File(filePath).readAsBytes();
final document = PdfDocument(inputBytes: bytes);
try {
if (pageIndex < 0 || pageIndex >= document.pages.count) {
return false;
}
document.pages.removeAt(pageIndex);
final outputBytes = await document.save();
await File(filePath).writeAsBytes(outputBytes, flush: true);
return true;
} finally {
document.dispose();
}
} catch (_) {
return false;
}
}
/// Insert a blank A4 page (595 x 842 pt) after [afterIndex].
/// Returns true on success.
Future<bool> insertBlankPage(String filePath, int afterIndex) async {
try {
final bytes = await File(filePath).readAsBytes();
final document = PdfDocument(inputBytes: bytes);
final insertAt = (afterIndex + 1).clamp(0, document.pages.count);
document.pages.insert(insertAt);
final outputBytes = await document.save();
document.dispose();
await File(filePath).writeAsBytes(outputBytes, flush: true);
return true;
} catch (_) {
return false;
}
}
/// Rotate page at [pageIndex] 90 degrees clockwise.
/// Returns true on success.
Future<bool> rotatePage(String filePath, int pageIndex) async {
try {
final bytes = await File(filePath).readAsBytes();
final document = PdfDocument(inputBytes: bytes);
try {
if (pageIndex < 0 || pageIndex >= document.pages.count) {
return false;
}
final page = document.pages[pageIndex];
final current = page.rotation;
// Cycle through: 0 -> 90 -> 180 -> 270 -> 0
switch (current) {
case PdfPageRotateAngle.rotateAngle0:
page.rotation = PdfPageRotateAngle.rotateAngle90;
case PdfPageRotateAngle.rotateAngle90:
page.rotation = PdfPageRotateAngle.rotateAngle180;
case PdfPageRotateAngle.rotateAngle180:
page.rotation = PdfPageRotateAngle.rotateAngle270;
case PdfPageRotateAngle.rotateAngle270:
page.rotation = PdfPageRotateAngle.rotateAngle0;
}
final outputBytes = await document.save();
await File(filePath).writeAsBytes(outputBytes, flush: true);
return true;
} finally {
document.dispose();
}
} catch (_) {
return false;
}
}
/// Draw an image from [imagePath] onto the page at [pageIndex],
/// fitted to the page dimensions while preserving aspect ratio.
/// Returns the [pdfPath] on success, null on failure.
Future<String?> insertImageOnPage(
String pdfPath,
int pageIndex,
String imagePath,
) async {
try {
final pdfBytes = await File(pdfPath).readAsBytes();
final document = PdfDocument(inputBytes: pdfBytes);
try {
if (pageIndex < 0 || pageIndex >= document.pages.count) {
return null;
}
final page = document.pages[pageIndex];
final imageBytes = await File(imagePath).readAsBytes();
final pdfImage = PdfBitmap(imageBytes);
final pageSize = page.getClientSize();
// Fit the image to the page while preserving its aspect ratio
// (letterboxed and centered), rather than stretching it to fill.
final imageWidth = pdfImage.width.toDouble();
final imageHeight = pdfImage.height.toDouble();
final scale = (imageWidth <= 0 || imageHeight <= 0)
? 1.0
: math.min(
pageSize.width / imageWidth,
pageSize.height / imageHeight,
);
final drawWidth = imageWidth * scale;
final drawHeight = imageHeight * scale;
final left = (pageSize.width - drawWidth) / 2;
final top = (pageSize.height - drawHeight) / 2;
page.graphics.drawImage(
pdfImage,
Rect.fromLTWH(left, top, drawWidth, drawHeight),
);
final outputBytes = await document.save();
await File(pdfPath).writeAsBytes(outputBytes, flush: true);
return pdfPath;
} finally {
document.dispose();
}
} catch (_) {
return null;
}
}
/// Renders [strokes] onto a PDF [page] using normalized [0, 1] coordinates
/// scaled to the actual page dimensions.
///
/// Freehand tools (pen, marker, highlighter) are rendered as filled outline
/// polygons produced by perfect_freehand's [getStroke], matching the
/// on-screen filled-nib appearance. Shape tools and text keep their existing
/// pen-stroke semantics.
void _renderStrokes(PdfPage page, List<InkStroke> strokes) {
final graphics = page.graphics;
final pageSize = page.getClientSize();
for (final stroke in strokes) {
if (stroke.points.isEmpty) continue;
final color = stroke.color;
final r = (color >> 16) & 0xFF;
final g = (color >> 8) & 0xFF;
final b = color & 0xFF;
final a = (color >> 24) & 0xFF;
final pdfColor = PdfColor(r, g, b, a);
final isFreehand = stroke.tool == PenTool.pen ||
stroke.tool == PenTool.marker ||
stroke.tool == PenTool.highlighter;
if (isFreehand) {
final brush = PdfSolidBrush(pdfColor);
if (stroke.points.length == 1) {
// Single point — filled dot matching stroke width.
final pt = stroke.points.first;
final radius = stroke.strokeWidth / 2;
graphics.drawEllipse(
Rect.fromCenter(
center: Offset(pt.x * pageSize.width, pt.y * pageSize.height),
width: radius * 2,
height: radius * 2,
),
brush: brush,
);
} else {
final pdfPath = _buildFreehandPdfPath(stroke, pageSize);
if (pdfPath != null) {
graphics.drawPath(pdfPath, brush: brush);
}
}
} else {
// Shape tools and text: keep existing pen-segment semantics.
final pen = PdfPen(pdfColor);
pen.width = stroke.strokeWidth.clamp(1.0, 8.0);
if (stroke.points.length == 1) {
final pt = stroke.points.first;
graphics.drawEllipse(
Rect.fromCenter(
center: Offset(pt.x * pageSize.width, pt.y * pageSize.height),
width: stroke.strokeWidth,
height: stroke.strokeWidth,
),
pen: pen,
);
} else {
for (int i = 0; i < stroke.points.length - 1; i++) {
final p1 = stroke.points[i];
final p2 = stroke.points[i + 1];
graphics.drawLine(
pen,
Offset(p1.x * pageSize.width, p1.y * pageSize.height),
Offset(p2.x * pageSize.width, p2.y * pageSize.height),
);
}
}
}
}
}
/// Builds a [PdfPath] filled outline polygon for a freehand [stroke] using
/// perfect_freehand's [getStroke], matching the on-screen recipe from
/// [lib/editor/engine/stroke_geometry.dart].
///
/// Points are scaled from normalized [0,1] coords into PDF-point space
/// defined by [pageSize] before being passed to [getStroke], so the
/// resulting outline is already in PDF coordinates.
///
/// Returns null when [getStroke] produces an empty outline.
PdfPath? _buildFreehandPdfPath(InkStroke stroke, Size pageSize) {
final isHighlighter = stroke.tool == PenTool.highlighter;
final pixelWidth = stroke.strokeWidth * pageSize.width;
// Detect real stylus pressure: the InkPoint default is 0.5, so any point
// that differs from the default indicates actual device pressure data.
final hasRealPressure = stroke.points.any((pt) => pt.pressure != 0.5);
final pfPoints = stroke.points
.map(
(pt) => pf.PointVector(
pt.x * pageSize.width,
pt.y * pageSize.height,
pt.pressure,
),
)
.toList();
final outline = pf.getStroke(
pfPoints,
options: pf.StrokeOptions(
size: pixelWidth,
// Highlighter keeps constant width; pen/marker taper via thinning=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. Highlighter never simulates.
simulatePressure: !hasRealPressure && !isHighlighter,
isComplete: true,
),
);
if (outline.isEmpty) return null;
final path = PdfPath();
// outline is already List<Offset> in perfect_freehand 2.x.
path.addPolygon(outline.toList());
return path;
}
}