Files
BadNote/lib/services/pdf_service.dart
Akiba So 0feca74278
All checks were successful
CI / Windows build (push) Successful in 14m54s
feat(pen): extensible brush model (4 brushes)
Replace the 2-tool ink system with a data-driven, Krita-style
BrushProfile (lib/editor/engine/brush.dart). Adding a brush is a
const map entry, not render-path branching.

Four presets from the rnote/krita spec:
- fountain pen: quadratic (p^2) pressure, wide dynamic width
- ballpoint:    near-constant width (thinning 0.15)
- highlighter:  flat width, square caps
- pencil:       sqrt(p) pressure, moderate width

Pressure is pre-warped per brush via PressureCurve(gamma) before
perfect_freehand; geometry fields (thinning/streamline/smoothing/
caps) flow through the shared stroke recipe so the PDF overlay and
the note/slide PenCanvas both honor the brush. Brush kind is now
persisted on the stroke model. Picker added to all three toolbars.

Opacity/multiply and pencil grain are carried as data but not yet
composited (TODO brush-opacity / brush-texture); this increment is
width + pressure-curve differentiation. analyze clean, 283 tests.
2026-06-24 11:13:43 +08:00

333 lines
12 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 '../editor/engine/stroke_geometry.dart' show freehandOutlinePoints;
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();
// ONE shared recipe with the on-screen painter (R7): export can no longer
// drift from screen. Previously this hardcoded thinning:0.7/streamline:0.5,
// which diverged from the screen's 0.85/0.32 → hairline export mismatch.
//
// TODO(brush-persist) / TODO(brush-export): InkStroke does not persist the
// brush, so export can only use the legacy (no-brush) recipe — it does NOT
// yet pass `brush:` here. Once the brush is persisted on InkStroke, resolve
// brushProfileFor(stroke.brush) and pass it so export matches the brush-aware
// screen geometry (taper/caps/per-brush thinning) for non-fountain brushes.
final outline = freehandOutlinePoints(
pfPoints: pfPoints,
size: pixelWidth,
isHighlighter: isHighlighter,
hasRealPressure: hasRealPressure,
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;
}
}