Files
BadNote/lib/services/pdf_service.dart
Akiba So 72428dc075
Some checks failed
CI / Test (Server, optional) (push) Failing after 2m10s
Windows Build / Build Windows (x64) (push) Failing after 29s
CI / Test (Flutter, Linux) (push) Has been cancelled
CI / Analyze (Flutter) (push) Has been cancelled
Fix bugs across app + server, optimize UI/UX, add Gitea CI
Bug fixes (Flutter):
- Wrap multi-statement DB writes (insert/update/delete note, deleteDocument,
  deletePageData, OCR FTS merge, migrations) in transactions to prevent data
  loss on interruption and a read-modify-write FTS race.
- Fix PdfDocument leaks on exception (try/finally dispose) and preserve image
  aspect ratio when stamping images onto PDF pages.
- Guard file-picker against empty selection (was .single -> crash).
- Fix eraser ConcurrentModificationError and unmodifiable-list crash on PDF
  pages; capture page synchronously on save to stop wrong-page data loss.
- Fix Riverpod DB-not-ready races, broken pull-to-refresh, settings load race,
  and search N+1; transform stored annotations on PDF page rotation.
- Normalize pen pressure for devices without a pressure range.
- PPT: single source of truth for slide strokes so ink displays and exports.

UI/UX:
- Material 3 typography, theme-aware colors (dark-mode fixes), hover cursors
  and right-click/visible actions on desktop, keyboard shortcuts (undo/redo/
  save/find), toolbar overflow handling, friendlier empty states, semantic OCR
  status badges, relative timestamps, 1-based page indicators, large-deck PPT
  navigation, and a scratchpad-scope label in split view.

Server (optional backend):
- Persist JWT secret (was per-process random), block path traversal in storage,
  fix CORS '*'+credentials, add OCR job ownership checks, last-writer-wins sync
  guard, constant-time login, and split out heavy OCR deps so the API/tests run
  without them.

CI: Gitea workflows for format+analyze+test (Linux, system sqlite) and a
Windows release build; pristine `flutter analyze`, all Flutter and server tests
green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-21 03:18:00 +08:00

246 lines
8.2 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:syncfusion_flutter_pdf/pdf.dart';
import '../models/ink_stroke.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.
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 pen = PdfPen(PdfColor(r, g, b, a));
pen.width = stroke.strokeWidth.clamp(1.0, 8.0);
if (stroke.points.length == 1) {
// Single point — draw a dot
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 {
// Draw line segments between consecutive points
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),
);
}
}
}
}
}