From 81018f58fcfdb0d80060b733e35bab0d55cf9172 Mon Sep 17 00:00:00 2001 From: Mayank37408 Date: Fri, 13 Nov 2026 14:08:32 +0530 Subject: [PATCH 1/2] feat: implement split PDF functionality (closes #23) --- .../presentation/tool_flow_screen.dart | 1319 ++++++++++++++++- lib/services/pdf_split_service.dart | 766 ++++++++++ .../processing/local_processing_service.dart | 35 + .../processing/processing_service.dart | 7 + test/unit/pdf_split_service_test.dart | 286 ++++ 5 files changed, 2398 insertions(+), 15 deletions(-) create mode 100644 lib/services/pdf_split_service.dart create mode 100644 test/unit/pdf_split_service_test.dart diff --git a/lib/features/tool_flow/presentation/tool_flow_screen.dart b/lib/features/tool_flow/presentation/tool_flow_screen.dart index ccccf8a..388c1a6 100644 --- a/lib/features/tool_flow/presentation/tool_flow_screen.dart +++ b/lib/features/tool_flow/presentation/tool_flow_screen.dart @@ -15,6 +15,7 @@ import '../../../services/file_validation_service.dart'; import '../../../services/image_conversion_service.dart'; import '../../../services/pdf_compression_service.dart'; import '../../../services/pdf_merge_service.dart'; +import '../../../services/pdf_split_service.dart'; import '../../files/data/files_repository.dart'; import '../../files/domain/saved_document.dart'; import '../../home/domain/tool_item.dart'; @@ -87,12 +88,37 @@ class _ToolFlowScreenState extends ConsumerState { bool _isMergedSavedToFiles = false; bool _isSavingMergedPdf = false; + // Split PDF state + final PdfSplitService _splitService = const PdfSplitService(); + final TextEditingController _splitPrefixController = TextEditingController(); + final TextEditingController _splitRangesController = TextEditingController(); + final TextEditingController _splitEveryNController = + TextEditingController(text: '2'); + final TextEditingController _splitPartsController = + TextEditingController(text: '2'); + SplitMode _splitMode = SplitMode.customRanges; + int _splitTotalPages = 1; + bool _splitIsEncrypted = false; + SplitValidationResult _splitValidation = + const SplitValidationResult(isValid: false); + bool _isSplitting = false; + String _splitStage = ''; + double? _splitProgress; + String? _splitError; + SplitPdfResult? _splitResult; + bool _isSplitSavedToFiles = false; + bool _isSavingSplitPdf = false; + // Multi-tool files state final List _selectedFiles = []; @override void dispose() { _mergeOutputNameController.dispose(); + _splitPrefixController.dispose(); + _splitRangesController.dispose(); + _splitEveryNController.dispose(); + _splitPartsController.dispose(); super.dispose(); } @@ -125,6 +151,9 @@ class _ToolFlowScreenState extends ConsumerState { _currentStepIndex = 1; } else { _selectedFiles.add(file); + if (widget.toolId == 'split_pdf') { + _inspectAndInitSplit(file); + } if (widget.toolId != 'merge_pdf') { _currentStepIndex = 1; } @@ -136,6 +165,7 @@ class _ToolFlowScreenState extends ConsumerState { bool get _isImageConvert => widget.toolId == 'image_convert'; bool get _isCompressPdf => widget.toolId == 'compress_pdf'; bool get _isMergePdf => widget.toolId == 'merge_pdf'; + bool get _isSplitPdf => widget.toolId == 'split_pdf'; Future _pickImage(ImageSource source) async { try { @@ -344,6 +374,9 @@ class _ToolFlowScreenState extends ConsumerState { } _selectedFiles.addAll(validFiles); }); + if (_isSplitPdf && validFiles.isNotEmpty) { + _inspectAndInitSplit(validFiles.first); + } } } } catch (e) { @@ -480,6 +513,9 @@ class _ToolFlowScreenState extends ConsumerState { _selectedFiles.clear(); _selectedFiles.add(file); }); + if (_isSplitPdf) { + _inspectAndInitSplit(file); + } } } else { final selectedDocIds = {}; @@ -868,6 +904,22 @@ class _ToolFlowScreenState extends ConsumerState { _mergeResult = null; _isMergedSavedToFiles = false; + _splitPrefixController.clear(); + _splitRangesController.clear(); + _splitEveryNController.text = '2'; + _splitPartsController.text = '2'; + _splitMode = SplitMode.customRanges; + _splitTotalPages = 1; + _splitIsEncrypted = false; + _splitValidation = const SplitValidationResult(isValid: false); + _isSplitting = false; + _splitStage = ''; + _splitProgress = null; + _splitError = null; + _splitResult = null; + _isSplitSavedToFiles = false; + _isSavingSplitPdf = false; + _selectedFiles.clear(); }); } @@ -1056,6 +1108,237 @@ class _ToolFlowScreenState extends ConsumerState { } } + Future _inspectAndInitSplit(File file) async { + try { + final inspection = await _splitService.inspectPdf(file.path); + final rawName = file.uri.pathSegments.isNotEmpty + ? file.uri.pathSegments.last + : 'document.pdf'; + final dotIdx = rawName.lastIndexOf('.'); + final baseName = dotIdx > 0 ? rawName.substring(0, dotIdx) : rawName; + + if (mounted) { + setState(() { + _splitTotalPages = + inspection.pageCount > 0 ? inspection.pageCount : 1; + _splitIsEncrypted = inspection.isEncrypted; + if (_splitPrefixController.text.isEmpty) { + _splitPrefixController.text = baseName; + } + if (_splitRangesController.text.isEmpty) { + _splitRangesController.text = '1-$_splitTotalPages'; + } + _splitError = null; + }); + _updateSplitValidation(); + } + } catch (e) { + if (mounted) { + setState(() { + _splitError = 'Failed to inspect PDF: $e'; + }); + } + } + } + + void _updateSplitValidation() { + setState(() { + switch (_splitMode) { + case SplitMode.customRanges: + _splitValidation = SplitRangeValidator.validateRanges( + _splitRangesController.text, + _splitTotalPages, + ); + break; + case SplitMode.everyNPages: + final n = int.tryParse(_splitEveryNController.text.trim()) ?? 1; + _splitValidation = SplitRangeValidator.validateEveryNPages( + n, + _splitTotalPages, + ); + break; + case SplitMode.extractAllPages: + _splitValidation = SplitRangeValidator.validateExtractAllPages( + _splitTotalPages, + ); + break; + case SplitMode.splitIntoNParts: + final parts = int.tryParse(_splitPartsController.text.trim()) ?? 2; + _splitValidation = SplitRangeValidator.validateSplitIntoNParts( + parts, + _splitTotalPages, + ); + break; + } + }); + } + + Future _promptOrStartSplit() async { + if (!_splitValidation.isValid || _selectedFiles.isEmpty) return; + + // 1. Check for 15+ files warning + if (_splitValidation.fileCount >= 15) { + final proceed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('High File Count'), + content: Text( + 'This split will create ${_splitValidation.fileCount} separate PDF files.\n\nAre you sure you want to proceed?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of(ctx).pop(true), + child: const Text('Proceed'), + ), + ], + ), + ); + if (proceed != true) return; + if (!mounted) return; + } + + // 2. Check for gap confirmation (> 2 omitted pages in customRanges) + if (_splitMode == SplitMode.customRanges && + _splitValidation.hasSignificantGap && + _splitValidation.omittedRangesSummary != null) { + final proceed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Omitted Pages Detected'), + content: Text( + 'Pages ${_splitValidation.omittedRangesSummary} won\'t be included in any output file.\n\nDo you want to continue?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(ctx).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + onPressed: () => Navigator.of(ctx).pop(true), + child: const Text('Continue'), + ), + ], + ), + ); + if (proceed != true) return; + if (!mounted) return; + } + + _startSplit(); + } + + Future _startSplit() async { + if (_selectedFiles.isEmpty || _isSplitting) return; + + final file = _selectedFiles.first; + if (!await file.exists()) { + setState(() { + _splitError = 'Selected PDF file no longer exists on disk.'; + }); + return; + } + + setState(() { + _isSplitting = true; + _splitStage = 'Preparing split...'; + _splitProgress = 0.05; + _splitError = null; + _splitResult = null; + _isSplitSavedToFiles = false; + _currentStepIndex = 2; + }); + + try { + final groups = _splitValidation.groups; + final prefix = _splitPrefixController.text.trim(); + + final result = await _splitService.splitPdf( + inputPath: file.path, + groups: groups, + outputPrefix: prefix.isNotEmpty ? prefix : null, + onProgress: (status, progress) { + if (mounted) { + setState(() { + _splitStage = status; + _splitProgress = progress; + }); + } + }, + ); + + if (mounted) { + setState(() { + _splitResult = result; + _isSplitting = false; + _currentStepIndex = 3; + }); + } + } catch (e) { + if (mounted) { + setState(() { + _splitError = e.toString(); + _isSplitting = false; + }); + } + } + } + + Future _handleSaveAllSplitPdfs() async { + if (_splitResult == null || _isSplitSavedToFiles || _isSavingSplitPdf) { + return; + } + setState(() => _isSavingSplitPdf = true); + + try { + int savedCount = 0; + for (final out in _splitResult!.outputFiles) { + final f = File(out.outputPath); + if (await f.exists()) { + await ref.read(savedFilesProvider.notifier).addExternalFile( + f, + customTitle: out.fileName, + sourceType: SavedDocumentSource.split, + ); + savedCount++; + } + } + + if (mounted) { + setState(() { + _isSplitSavedToFiles = true; + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Saved $savedCount PDF files to Saved Documents.'), + backgroundColor: Colors.green.shade700, + ), + ); + } + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Failed to save split files: $e')), + ); + } + } finally { + if (mounted) { + setState(() => _isSavingSplitPdf = false); + } + } + } + + Future _handleShareAllSplitPdfs() async { + if (_splitResult == null || _splitResult!.outputFiles.isEmpty) return; + final xfiles = + _splitResult!.outputFiles.map((f) => XFile(f.outputPath)).toList(); + // ignore: deprecated_member_use + await Share.shareXFiles(xfiles); + } + @override Widget build(BuildContext context) { final tool = ToolItem.findById(widget.toolId); @@ -1077,6 +1360,10 @@ class _ToolFlowScreenState extends ConsumerState { canGoNext = (_currentStepIndex == 0 && _selectedFiles.isNotEmpty) || (_currentStepIndex == 1); + } else if (_isSplitPdf) { + canGoNext = + (_currentStepIndex == 0 && _selectedFiles.isNotEmpty) || + (_currentStepIndex == 1 && _splitValidation.isValid && !_isSplitting); } else if (widget.toolId == 'office_to_pdf') { // Office to PDF is UI scaffolding only in this phase canGoNext = false; @@ -1116,7 +1403,7 @@ class _ToolFlowScreenState extends ConsumerState { return Expanded( child: InkWell( onTap: () { - if (_isConverting || _isCompressing) return; + if (_isConverting || _isCompressing || _isMerging || _isSplitting) return; if (_isImageConvert) { if (index == 0) { setState(() => _currentStepIndex = index); @@ -1154,6 +1441,19 @@ class _ToolFlowScreenState extends ConsumerState { } else if (index == 3 && _mergeResult != null) { setState(() => _currentStepIndex = index); } + } else if (_isSplitPdf) { + if (index == 0) { + setState(() => _currentStepIndex = index); + } else if (index == 1 && + _selectedFiles.isNotEmpty) { + setState(() => _currentStepIndex = index); + } else if (index == 2 && + _selectedFiles.isNotEmpty && + _splitValidation.isValid) { + _promptOrStartSplit(); + } else if (index == 3 && _splitResult != null) { + setState(() => _currentStepIndex = index); + } } else { if (index == 0) { setState(() => _currentStepIndex = index); @@ -1197,28 +1497,34 @@ class _ToolFlowScreenState extends ConsumerState { // Active Step View Expanded( child: Padding( - padding: const EdgeInsets.all(20), - child: Center( - child: SingleChildScrollView( - child: _buildStepContent(context, borderColor, isDark), - ), - ), + padding: _isSplitPdf && _currentStepIndex == 3 + ? const EdgeInsets.fromLTRB(16, 12, 16, 0) + : const EdgeInsets.all(20), + child: _isSplitPdf && _currentStepIndex == 3 + ? _buildSplitPdfResultStep(context, borderColor, isDark) + : Center( + child: SingleChildScrollView( + child: _buildStepContent(context, borderColor, isDark), + ), + ), ), ), // Step Navigation Bar - Container( - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - border: Border(top: BorderSide(color: borderColor, width: 1)), - ), - child: Row( + if (!(_isSplitPdf && _currentStepIndex == 3)) + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: borderColor, width: 1)), + ), + child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (_currentStepIndex > 0 && !_isConverting && !_isCompressing && - !_isMerging) + !_isMerging && + !_isSplitting) OutlinedButton( onPressed: () => setState(() => _currentStepIndex--), child: const Text('Back'), @@ -1237,8 +1543,18 @@ class _ToolFlowScreenState extends ConsumerState { } else if (_isMergePdf && _currentStepIndex == 1) { _startMerge(); + } else if (_isSplitPdf && + _currentStepIndex == 1) { + _promptOrStartSplit(); } else { - setState(() => _currentStepIndex++); + setState(() { + _currentStepIndex++; + if (_isSplitPdf && + _currentStepIndex == 1 && + _selectedFiles.isNotEmpty) { + _inspectAndInitSplit(_selectedFiles.first); + } + }); } } : null, @@ -1249,6 +1565,8 @@ class _ToolFlowScreenState extends ConsumerState { ? 'Compress PDF' : _isMergePdf && _currentStepIndex == 1 ? 'Merge PDF' + : _isSplitPdf && _currentStepIndex == 1 + ? 'Split PDF' : 'Next step', ), ) @@ -1260,6 +1578,8 @@ class _ToolFlowScreenState extends ConsumerState { ? 'Compress another' : _isMergePdf ? 'Merge another' + : _isSplitPdf + ? 'Split another' : 'Convert another', ), ), @@ -1323,6 +1643,21 @@ class _ToolFlowScreenState extends ConsumerState { } } + if (_isSplitPdf) { + switch (_currentStepIndex) { + case 0: + return _buildSelectFilesStep(context, borderColor, isDark); + case 1: + return _buildSplitPdfOptionsStep(context, borderColor, isDark); + case 2: + return _buildSplitPdfProgressStep(context, borderColor, isDark); + case 3: + return _buildSplitPdfResultStep(context, borderColor, isDark); + default: + return const SizedBox.shrink(); + } + } + switch (_currentStepIndex) { case 0: return _buildSelectFilesStep(context, borderColor, isDark); @@ -3429,6 +3764,960 @@ class _ToolFlowScreenState extends ConsumerState { ); } + Widget _buildSplitPdfOptionsStep( + BuildContext context, + Color borderColor, + bool isDark, + ) { + if (_selectedFiles.isEmpty) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.warning_amber_rounded, + size: 36, + color: Colors.orange, + ), + const SizedBox(height: 12), + const Text( + 'No PDF file selected.', + style: TextStyle(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 12), + OutlinedButton( + onPressed: () => setState(() => _currentStepIndex = 0), + child: const Text('Back to file selection'), + ), + ], + ); + } + + final file = _selectedFiles.first; + final fileName = file.uri.pathSegments.isNotEmpty + ? file.uri.pathSegments.last + : 'document.pdf'; + final fileSizeBytes = file.existsSync() ? file.lengthSync() : 0; + final formattedSize = fileSizeBytes < 1024 * 1024 + ? '${(fileSizeBytes / 1024).toStringAsFixed(1)} KB' + : '${(fileSizeBytes / (1024 * 1024)).toStringAsFixed(2)} MB'; + + return SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // File summary card + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF141414) : const Color(0xFFF9F9F9), + border: Border.all(color: borderColor, width: 1), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: const Color(0xFF007AFF).withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(6), + ), + child: const Icon( + Icons.call_split_outlined, + color: Color(0xFF007AFF), + size: 22, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + fileName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 3), + Text( + '$formattedSize • $_splitTotalPages ${_splitTotalPages == 1 ? 'page' : 'pages'}' + '${_splitIsEncrypted ? ' • Password-protected' : ''}', + style: TextStyle( + fontSize: 12, + color: isDark ? Colors.white60 : Colors.black54, + ), + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 20), + + // Splitting mode selection + Text( + 'Splitting Mode', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Custom Ranges'), + selected: _splitMode == SplitMode.customRanges, + onSelected: (val) { + if (val) { + setState(() => _splitMode = SplitMode.customRanges); + _updateSplitValidation(); + } + }, + ), + ChoiceChip( + label: const Text('Every N Pages'), + selected: _splitMode == SplitMode.everyNPages, + onSelected: (val) { + if (val) { + setState(() => _splitMode = SplitMode.everyNPages); + _updateSplitValidation(); + } + }, + ), + ChoiceChip( + label: const Text('Extract All Pages'), + selected: _splitMode == SplitMode.extractAllPages, + onSelected: (val) { + if (val) { + setState(() => _splitMode = SplitMode.extractAllPages); + _updateSplitValidation(); + } + }, + ), + ChoiceChip( + label: const Text('Split into N Parts'), + selected: _splitMode == SplitMode.splitIntoNParts, + onSelected: (val) { + if (val) { + setState(() => _splitMode = SplitMode.splitIntoNParts); + _updateSplitValidation(); + } + }, + ), + ], + ), + const SizedBox(height: 18), + + // Mode-specific configuration + if (_splitMode == SplitMode.customRanges) ...[ + Text( + 'Page Ranges', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(height: 6), + TextField( + controller: _splitRangesController, + decoration: InputDecoration( + hintText: 'e.g. 1-3, 5, 8-10', + helperText: + 'Comma-separated groups (1-$_splitTotalPages). Each group becomes its own file.', + border: const OutlineInputBorder(), + isDense: true, + ), + onChanged: (_) => _updateSplitValidation(), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 6, + children: [ + ActionChip( + label: Text('All (1-$_splitTotalPages)'), + onPressed: () { + _splitRangesController.text = '1-$_splitTotalPages'; + _updateSplitValidation(); + }, + ), + if (_splitTotalPages >= 2) ...[ + ActionChip( + label: Text('First half (1-${_splitTotalPages ~/ 2})'), + onPressed: () { + _splitRangesController.text = + '1-${_splitTotalPages ~/ 2}'; + _updateSplitValidation(); + }, + ), + ActionChip( + label: Text( + 'Second half (${(_splitTotalPages ~/ 2) + 1}-$_splitTotalPages)', + ), + onPressed: () { + _splitRangesController.text = + '${(_splitTotalPages ~/ 2) + 1}-$_splitTotalPages'; + _updateSplitValidation(); + }, + ), + ], + ], + ), + ] else if (_splitMode == SplitMode.everyNPages) ...[ + Text( + 'Pages per file (N)', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(height: 6), + Row( + children: [ + IconButton.outlined( + onPressed: () { + final curr = + int.tryParse(_splitEveryNController.text.trim()) ?? 1; + if (curr > 1) { + _splitEveryNController.text = '${curr - 1}'; + _updateSplitValidation(); + } + }, + icon: const Icon(Icons.remove, size: 18), + ), + const SizedBox(width: 8), + SizedBox( + width: 90, + child: TextField( + controller: _splitEveryNController, + keyboardType: TextInputType.number, + textAlign: TextAlign.center, + decoration: const InputDecoration( + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (_) => _updateSplitValidation(), + ), + ), + const SizedBox(width: 8), + IconButton.outlined( + onPressed: () { + final curr = + int.tryParse(_splitEveryNController.text.trim()) ?? 1; + if (curr < _splitTotalPages) { + _splitEveryNController.text = '${curr + 1}'; + _updateSplitValidation(); + } + }, + icon: const Icon(Icons.add, size: 18), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'Splits document into sequential chunks of N pages.', + style: TextStyle( + fontSize: 12, + color: isDark ? Colors.white54 : Colors.black54, + ), + ), + ] else if (_splitMode == SplitMode.extractAllPages) ...[ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF1F1F1F) : const Color(0xFFF0F0F0), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + children: [ + const Icon( + Icons.info_outline, + size: 20, + color: Color(0xFF007AFF), + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Every page will be saved as its own individual 1-page PDF file ($_splitTotalPages files total).', + style: const TextStyle(fontSize: 13), + ), + ), + ], + ), + ), + ] else if (_splitMode == SplitMode.splitIntoNParts) ...[ + Text( + 'Number of equal parts (N)', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(height: 6), + Row( + children: [ + IconButton.outlined( + onPressed: () { + final curr = + int.tryParse(_splitPartsController.text.trim()) ?? 2; + if (curr > 2) { + _splitPartsController.text = '${curr - 1}'; + _updateSplitValidation(); + } + }, + icon: const Icon(Icons.remove, size: 18), + ), + const SizedBox(width: 8), + SizedBox( + width: 90, + child: TextField( + controller: _splitPartsController, + keyboardType: TextInputType.number, + textAlign: TextAlign.center, + decoration: const InputDecoration( + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (_) => _updateSplitValidation(), + ), + ), + const SizedBox(width: 8), + IconButton.outlined( + onPressed: () { + final curr = + int.tryParse(_splitPartsController.text.trim()) ?? 2; + if (curr < _splitTotalPages) { + _splitPartsController.text = '${curr + 1}'; + _updateSplitValidation(); + } + }, + icon: const Icon(Icons.add, size: 18), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'Evenly distributes the $_splitTotalPages pages into N separate PDF files.', + style: TextStyle( + fontSize: 12, + color: isDark ? Colors.white54 : Colors.black54, + ), + ), + ], + + const SizedBox(height: 18), + + // Output Filename Prefix + Text( + 'Output Filename Prefix', + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + const SizedBox(height: 6), + TextField( + controller: _splitPrefixController, + decoration: const InputDecoration( + hintText: 'e.g. document', + helperText: + 'Output files: [prefix]_pages_1-3.pdf (or _part1_pages_...)', + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (_) => setState(() {}), + ), + + const SizedBox(height: 20), + + // Live Preview Card + Container( + width: double.infinity, + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF141414) : const Color(0xFFF9F9F9), + border: Border.all( + color: !_splitValidation.isValid + ? Colors.red.shade400 + : (_splitValidation.hasSignificantGap + ? Colors.amber.shade600 + : borderColor), + width: 1, + ), + borderRadius: BorderRadius.circular(8), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + !_splitValidation.isValid + ? Icons.error_outline + : (_splitValidation.hasSignificantGap + ? Icons.warning_amber_rounded + : Icons.preview_outlined), + size: 20, + color: !_splitValidation.isValid + ? Colors.red + : (_splitValidation.hasSignificantGap + ? Colors.amber.shade700 + : const Color(0xFF007AFF)), + ), + const SizedBox(width: 8), + const Text( + 'Split Output Preview', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + ), + ), + const Spacer(), + if (_splitValidation.isValid) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2, + ), + decoration: BoxDecoration( + color: const Color(0xFF007AFF).withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(10), + ), + child: Text( + '${_splitValidation.fileCount} ${_splitValidation.fileCount == 1 ? 'file' : 'files'}', + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFF007AFF), + ), + ), + ), + ], + ), + if (!_splitValidation.isValid) ...[ + const SizedBox(height: 10), + Text( + _splitValidation.errorMessage ?? + 'Invalid split configuration.', + style: TextStyle( + color: Colors.red.shade400, + fontSize: 13, + fontWeight: FontWeight.w500, + ), + ), + ] else ...[ + if (_splitValidation.hasSignificantGap && + _splitValidation.omittedRangesSummary != null) ...[ + const SizedBox(height: 10), + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.amber.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + children: [ + Icon( + Icons.info_outline, + size: 16, + color: Colors.amber.shade800, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Pages ${_splitValidation.omittedRangesSummary} will be omitted from all output files. You\'ll confirm before splitting.', + style: TextStyle( + fontSize: 12, + color: Colors.amber.shade900, + ), + ), + ), + ], + ), + ), + ], + if (_splitValidation.fileCount >= 15) ...[ + const SizedBox(height: 10), + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.blue.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Row( + children: [ + const Icon( + Icons.info_outline, + size: 16, + color: Color(0xFF007AFF), + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Generating ${_splitValidation.fileCount} files requires confirmation before proceeding.', + style: const TextStyle( + fontSize: 12, + color: Color(0xFF007AFF), + ), + ), + ), + ], + ), + ), + ], + const SizedBox(height: 12), + const Divider(height: 1), + const SizedBox(height: 8), + ..._splitValidation.groups.take(8).map((grp) { + final prefix = _splitPrefixController.text.trim().isNotEmpty + ? _splitPrefixController.text.trim() + : 'document'; + final cleanRange = grp.rangeString.replaceAll(' ', ''); + final sampleName = '${prefix}_pages_$cleanRange.pdf'; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Container( + width: 24, + height: 24, + alignment: Alignment.center, + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF222222) + : const Color(0xFFEEEEEE), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + '${grp.index}', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + sampleName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + Text( + 'Pages ${grp.rangeString} (${grp.pageCount} ${grp.pageCount == 1 ? 'page' : 'pages'})', + style: TextStyle( + fontSize: 11, + color: isDark + ? Colors.white54 + : Colors.black54, + ), + ), + ], + ), + ), + ], + ), + ); + }), + if (_splitValidation.groups.length > 8) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text( + '+ ${_splitValidation.groups.length - 8} more files...', + style: TextStyle( + fontSize: 11, + fontStyle: FontStyle.italic, + color: isDark ? Colors.white54 : Colors.black54, + ), + ), + ), + ], + ], + ), + ), + const SizedBox(height: 20), + ], + ), + ); + } + + Widget _buildSplitPdfProgressStep( + BuildContext context, + Color borderColor, + bool isDark, + ) { + if (_splitError != null) { + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline, size: 40, color: Colors.red), + const SizedBox(height: 16), + const Text( + 'Split Failed', + style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Text( + _splitError!, + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 13, + color: isDark ? Colors.white70 : Colors.black87, + ), + ), + ), + const SizedBox(height: 20), + OutlinedButton.icon( + onPressed: () { + setState(() { + _splitError = null; + _currentStepIndex = 1; + }); + }, + icon: const Icon(Icons.refresh, size: 18), + label: const Text('Try Again'), + ), + ], + ); + } + + return Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const SizedBox( + width: 48, + height: 48, + child: CircularProgressIndicator(strokeWidth: 3), + ), + const SizedBox(height: 24), + Text( + _splitStage.isNotEmpty ? _splitStage : 'Splitting PDF...', + textAlign: TextAlign.center, + style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700), + ), + if (_splitProgress != null) ...[ + const SizedBox(height: 14), + SizedBox( + width: 240, + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: _splitProgress, + minHeight: 6, + ), + ), + ), + const SizedBox(height: 6), + Text( + '${((_splitProgress ?? 0.0) * 100).toInt()}%', + style: TextStyle( + fontSize: 12, + color: isDark ? Colors.white60 : Colors.black54, + ), + ), + ], + const SizedBox(height: 12), + Text( + 'Processing entirely on-device • 100% private', + style: TextStyle( + fontSize: 11, + color: isDark ? Colors.white38 : Colors.black38, + ), + ), + ], + ); + } + + Widget _buildSplitPdfResultStep( + BuildContext context, + Color borderColor, + bool isDark, + ) { + final res = _splitResult; + if (res == null) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Text('No split result available.'), + const SizedBox(height: 12), + OutlinedButton( + onPressed: () => setState(() => _currentStepIndex = 0), + child: const Text('Back to file selection'), + ), + ], + ), + ); + } + + final fileCount = res.outputFiles.length; + final fileCountText = + fileCount == 1 ? '1 PDF file' : '$fileCount PDF files'; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 1. Success Header + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), + decoration: BoxDecoration( + color: isDark ? const Color(0xFF141414) : const Color(0xFFF9F9F9), + border: Border.all(color: borderColor, width: 1), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Container( + width: 38, + height: 38, + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.15), + shape: BoxShape.circle, + ), + child: const Icon( + Icons.check_circle_outline, + color: Colors.green, + size: 22, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Successfully split into $fileCountText', + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + ), + ), + const SizedBox(height: 2), + Text( + 'Source: ${res.inputFileName} (${res.totalSourcePages} pages)', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 12, + color: isDark ? Colors.white60 : Colors.black54, + ), + ), + ], + ), + ), + ], + ), + ), + const SizedBox(height: 12), + + // 2. Scrollable List of Generated Files + Expanded( + child: ListView.separated( + itemCount: res.outputFiles.length, + separatorBuilder: (_, _) => const SizedBox(height: 8), + itemBuilder: (ctx, idx) { + final out = res.outputFiles[idx]; + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF141414) + : const Color(0xFFFBFBFB), + border: Border.all(color: borderColor, width: 1), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + children: [ + Container( + width: 32, + height: 32, + alignment: Alignment.center, + decoration: BoxDecoration( + color: const Color(0xFF007AFF).withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + '${out.partIndex}', + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: Color(0xFF007AFF), + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + out.fileName, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 4), + Wrap( + spacing: 6, + runSpacing: 4, + children: [ + // Page count badge + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF222222) + : const Color(0xFFEEEEEE), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + '${out.pageCount} ${out.pageCount == 1 ? 'page' : 'pages'} (pages ${out.sourceRange})', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: isDark + ? Colors.white70 + : Colors.black87, + ), + ), + ), + // File size badge + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: isDark + ? const Color(0xFF222222) + : const Color(0xFFEEEEEE), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + out.formattedSize, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: isDark + ? Colors.white70 + : Colors.black87, + ), + ), + ), + ], + ), + ], + ), + ), + IconButton( + tooltip: 'View PDF', + icon: const Icon(Icons.visibility_outlined, size: 18), + onPressed: () { + final encodedPath = Uri.encodeComponent(out.outputPath); + final encodedTitle = Uri.encodeComponent(out.fileName); + context.push( + '/pdf-viewer?path=$encodedPath&title=$encodedTitle', + ); + }, + ), + IconButton( + tooltip: 'Share', + icon: const Icon(Icons.share_outlined, size: 18), + onPressed: () { + // ignore: deprecated_member_use + Share.shareXFiles([XFile(out.outputPath)]); + }, + ), + ], + ), + ); + }, + ), + ), + const SizedBox(height: 12), + + // 3. Bottom Sticky Bar: Save All to Files, Share All, and Done + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric(vertical: 12), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: borderColor, width: 1)), + ), + child: Row( + children: [ + Expanded( + flex: 5, + child: ElevatedButton.icon( + onPressed: _isSplitSavedToFiles || _isSavingSplitPdf + ? null + : _handleSaveAllSplitPdfs, + icon: Icon( + _isSplitSavedToFiles ? Icons.check : Icons.save_alt_outlined, + size: 16, + ), + label: Text( + _isSavingSplitPdf + ? 'Saving...' + : (_isSplitSavedToFiles + ? 'Saved All' + : 'Save All to Files'), + ), + ), + ), + const SizedBox(width: 8), + Expanded( + flex: 4, + child: OutlinedButton.icon( + onPressed: _handleShareAllSplitPdfs, + icon: const Icon(Icons.share_outlined, size: 16), + label: const Text('Share All'), + ), + ), + const SizedBox(width: 8), + OutlinedButton( + onPressed: _resetFlow, + child: const Text('Done'), + ), + ], + ), + ), + ], + ); + } + Widget _buildPlaceholder({ required String title, required String subtitle, diff --git a/lib/services/pdf_split_service.dart b/lib/services/pdf_split_service.dart new file mode 100644 index 0000000..f6de3b2 --- /dev/null +++ b/lib/services/pdf_split_service.dart @@ -0,0 +1,766 @@ +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; +import 'dart:ui' show Offset; + +import 'package:path_provider/path_provider.dart'; +import 'package:syncfusion_flutter_pdf/pdf.dart' as sf; + +import '../core/constants/app_limits.dart'; + +/// Available splitting modes supported by KrocPDF. +enum SplitMode { + customRanges, + everyNPages, + extractAll, + equalParts; + + static const SplitMode extractAllPages = SplitMode.extractAll; + static const SplitMode splitIntoNParts = SplitMode.equalParts; +} + +/// Inspection result of a PDF document. +class PdfInspectionResult { + final int pageCount; + final bool isEncrypted; + + const PdfInspectionResult({ + required this.pageCount, + required this.isEncrypted, + }); +} + +/// Represents a single output group produced by splitting. +class SplitGroup { + final int partIndex; // 1-based index (e.g. 1 for Part 1) + final List pageNumbers; // 1-based page numbers in source document + final String label; // Human-friendly label, e.g. "Part 1: pages 1–3" + final String suggestedFileName; // e.g. "Document_pages_1-3.pdf" + + const SplitGroup({ + required this.partIndex, + required this.pageNumbers, + required this.label, + required this.suggestedFileName, + }); + + int get index => partIndex; + int get pageCount => pageNumbers.length; + + String get rangeString => pageNumbers.isEmpty + ? '' + : (pageNumbers.length == 1 + ? '${pageNumbers.first}' + : '${pageNumbers.first}–${pageNumbers.last}'); + + /// Returns 0-based page indices for internal PDF page operations. + List get pageIndices => pageNumbers.map((p) => p - 1).toList(); +} + +/// Validation result with live preview of parsed split groups. +class SplitValidationResult { + final bool isValid; + final String? errorMessage; + final List groups; + final List missingPages; // 1-based page numbers not in any group + final bool exceedsHardCap; // True if > 50 files + final bool requiresCountConfirmation; // True if > 15 files + + const SplitValidationResult({ + required this.isValid, + this.errorMessage, + this.groups = const [], + this.missingPages = const [], + this.exceedsHardCap = false, + this.requiresCountConfirmation = false, + }); + + bool get hasSignificantGap => missingPages.length > 2; + int get totalOutputFiles => groups.length; + int get fileCount => totalOutputFiles; + + String? get omittedRangesSummary => + missingPages.isEmpty ? null : formatMissingRanges(); + + /// Formats missing pages into friendly range strings (e.g. "4-7, 10"). + String formatMissingRanges() { + if (missingPages.isEmpty) return ''; + final ranges = []; + int? rangeStart; + int? prev; + + for (final p in missingPages) { + if (rangeStart == null) { + rangeStart = p; + prev = p; + } else if (p == prev! + 1) { + prev = p; + } else { + ranges.add(rangeStart == prev ? '$rangeStart' : '$rangeStart–$prev'); + rangeStart = p; + prev = p; + } + } + if (rangeStart != null) { + ranges.add(rangeStart == prev ? '$rangeStart' : '$rangeStart–$prev'); + } + return ranges.join(', '); + } +} + +/// Result metadata for an individual generated output PDF file. +class SplitOutputFile { + final int partIndex; + final String outputPath; + final String fileName; + final int fileSizeBytes; + final int pageCount; + final List pageNumbers; + + const SplitOutputFile({ + this.partIndex = 1, + required this.outputPath, + required this.fileName, + required this.fileSizeBytes, + required this.pageCount, + required this.pageNumbers, + }); + + String get sourceRange => pageNumbers.isEmpty + ? '' + : (pageNumbers.length == 1 + ? '${pageNumbers.first}' + : '${pageNumbers.first}–${pageNumbers.last}'); + + String get formattedSize { + if (fileSizeBytes < 1024) { + return '$fileSizeBytes B'; + } + if (fileSizeBytes < 1024 * 1024) { + return '${(fileSizeBytes / 1024).toStringAsFixed(1)} KB'; + } + return '${(fileSizeBytes / (1024 * 1024)).toStringAsFixed(2)} MB'; + } +} + +/// Result of a completed Split PDF operation. +class SplitPdfResult { + final List files; + final int totalSourcePages; + final String sourceFileName; + + const SplitPdfResult({ + required this.files, + required this.totalSourcePages, + required this.sourceFileName, + }); + + int get totalFiles => files.length; + List get outputFiles => files; + String get inputFileName => sourceFileName; +} + +/// Range parsing and validation engine. +class SplitRangeValidator { + static const int maxOutputFilesCap = 50; + static const int confirmationThreshold = 15; + + static SplitValidationResult validateRanges( + String input, + int totalPages, { + String prefix = 'document', + }) => + validate( + mode: SplitMode.customRanges, + totalPages: totalPages, + customRangesInput: input, + prefix: prefix, + ); + + static SplitValidationResult validateEveryNPages( + int n, + int totalPages, { + String prefix = 'document', + }) => + validate( + mode: SplitMode.everyNPages, + totalPages: totalPages, + everyN: n, + prefix: prefix, + ); + + static SplitValidationResult validateExtractAllPages( + int totalPages, { + String prefix = 'document', + }) => + validate( + mode: SplitMode.extractAll, + totalPages: totalPages, + prefix: prefix, + ); + + static SplitValidationResult validateSplitIntoNParts( + int parts, + int totalPages, { + String prefix = 'document', + }) => + validate( + mode: SplitMode.equalParts, + totalPages: totalPages, + equalParts: parts, + prefix: prefix, + ); + + /// Parses and validates page ranges for any of the 4 Split modes. + static SplitValidationResult validate({ + required SplitMode mode, + required int totalPages, + String? customRangesInput, + int? everyN, + int? equalParts, + String prefix = 'document', + }) { + if (totalPages <= 0) { + return const SplitValidationResult( + isValid: false, + errorMessage: 'Source document has no pages.', + ); + } + + final sanitizedPrefix = _sanitizePrefix(prefix); + + switch (mode) { + case SplitMode.extractAll: + return _buildExtractAll(totalPages, sanitizedPrefix); + case SplitMode.everyNPages: + return _buildEveryN(totalPages, everyN ?? 2, sanitizedPrefix); + case SplitMode.equalParts: + return _buildEqualParts(totalPages, equalParts ?? 2, sanitizedPrefix); + case SplitMode.customRanges: + return _buildCustomRanges( + totalPages, + customRangesInput ?? '', + sanitizedPrefix, + ); + } + } + + static String _sanitizePrefix(String raw) { + var p = raw.trim(); + if (p.toLowerCase().endsWith('.pdf')) { + p = p.substring(0, p.length - 4); + } + p = p.replaceAll(RegExp(r'[\\/:*?"<>|]'), '_'); + return p.isEmpty ? 'document' : p; + } + + static SplitValidationResult _buildExtractAll(int totalPages, String prefix) { + if (totalPages > maxOutputFilesCap) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Extract All would generate $totalPages files (maximum $maxOutputFilesCap allowed). Use Every N Pages or Page Ranges.', + exceedsHardCap: true, + ); + } + + final groups = []; + for (int p = 1; p <= totalPages; p++) { + groups.add( + SplitGroup( + partIndex: p, + pageNumbers: [p], + label: 'Page $p', + suggestedFileName: '${prefix}_page_$p.pdf', + ), + ); + } + + return SplitValidationResult( + isValid: true, + groups: groups, + missingPages: const [], + requiresCountConfirmation: totalPages > confirmationThreshold, + ); + } + + static SplitValidationResult _buildEveryN( + int totalPages, + int n, + String prefix, + ) { + if (n < 1) { + return const SplitValidationResult( + isValid: false, + errorMessage: 'Chunk size must be at least 1 page.', + ); + } + + final totalFiles = (totalPages / n).ceil(); + if (totalFiles > maxOutputFilesCap) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Splitting every $n pages would produce $totalFiles files (maximum $maxOutputFilesCap allowed). Increase chunk size.', + exceedsHardCap: true, + ); + } + + final groups = []; + int partIdx = 1; + for (int start = 1; start <= totalPages; start += n) { + final end = (start + n - 1).clamp(1, totalPages); + final pages = [for (int i = start; i <= end; i++) i]; + final rangeStr = start == end ? '$start' : '$start–$end'; + final fileRangeStr = start == end ? '$start' : '$start-$end'; + + groups.add( + SplitGroup( + partIndex: partIdx, + pageNumbers: pages, + label: 'Part $partIdx: pages $rangeStr', + suggestedFileName: '${prefix}_part${partIdx}_pages_$fileRangeStr.pdf', + ), + ); + partIdx++; + } + + return SplitValidationResult( + isValid: true, + groups: groups, + missingPages: const [], + requiresCountConfirmation: groups.length > confirmationThreshold, + ); + } + + static SplitValidationResult _buildEqualParts( + int totalPages, + int parts, + String prefix, + ) { + if (parts < 2) { + return const SplitValidationResult( + isValid: false, + errorMessage: 'Parts count must be at least 2.', + ); + } + if (parts > totalPages) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Cannot split $totalPages pages into $parts parts (more parts than pages).', + ); + } + if (parts > maxOutputFilesCap) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Cannot exceed $maxOutputFilesCap output files (requested $parts).', + exceedsHardCap: true, + ); + } + + final groups = []; + final baseSize = totalPages ~/ parts; + final remainder = totalPages % parts; + + int currentStart = 1; + for (int i = 0; i < parts; i++) { + final chunkSize = baseSize + (i < remainder ? 1 : 0); + final currentEnd = currentStart + chunkSize - 1; + final pages = [for (int p = currentStart; p <= currentEnd; p++) p]; + final rangeStr = currentStart == currentEnd + ? '$currentStart' + : '$currentStart–$currentEnd'; + final fileRangeStr = currentStart == currentEnd + ? '$currentStart' + : '$currentStart-$currentEnd'; + + groups.add( + SplitGroup( + partIndex: i + 1, + pageNumbers: pages, + label: 'Part ${i + 1}: pages $rangeStr', + suggestedFileName: + '${prefix}_part${i + 1}_pages_$fileRangeStr.pdf', + ), + ); + currentStart = currentEnd + 1; + } + + return SplitValidationResult( + isValid: true, + groups: groups, + missingPages: const [], + requiresCountConfirmation: parts > confirmationThreshold, + ); + } + + static SplitValidationResult _buildCustomRanges( + int totalPages, + String input, + String prefix, + ) { + final raw = input.trim(); + if (raw.isEmpty) { + return const SplitValidationResult( + isValid: false, + errorMessage: 'Enter one or more page ranges (e.g. 1-3, 5, 8-12).', + ); + } + + final segments = raw.split(','); + final groups = []; + final includedPages = {}; + int partIdx = 1; + + for (final seg in segments) { + final s = seg.trim(); + if (s.isEmpty) continue; + + if (s.contains('-')) { + final parts = s.split('-'); + if (parts.length != 2) { + return SplitValidationResult( + isValid: false, + errorMessage: 'Invalid range syntax "$s". Use format "start-end".', + ); + } + final start = int.tryParse(parts[0].trim()); + final end = int.tryParse(parts[1].trim()); + if (start == null || end == null) { + return SplitValidationResult( + isValid: false, + errorMessage: 'Range "$s" must contain valid numbers.', + ); + } + if (start < 1) { + return SplitValidationResult( + isValid: false, + errorMessage: 'Page numbers must be 1 or greater (got $start).', + ); + } + if (start > totalPages) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Page $start exceeds document page count of $totalPages.', + ); + } + if (end > totalPages) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Page $end exceeds document page count of $totalPages.', + ); + } + if (start > end) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Start page $start cannot be greater than end page $end in "$s".', + ); + } + + final pages = [for (int p = start; p <= end; p++) p]; + includedPages.addAll(pages); + final fileRangeStr = '$start-$end'; + groups.add( + SplitGroup( + partIndex: partIdx, + pageNumbers: pages, + label: 'Part $partIdx: pages $start–$end', + suggestedFileName: '${prefix}_pages_$fileRangeStr.pdf', + ), + ); + } else { + final single = int.tryParse(s); + if (single == null) { + return SplitValidationResult( + isValid: false, + errorMessage: 'Invalid page number "$s".', + ); + } + if (single < 1) { + return SplitValidationResult( + isValid: false, + errorMessage: 'Page number must be 1 or greater (got $single).', + ); + } + if (single > totalPages) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Page $single exceeds document page count of $totalPages.', + ); + } + + includedPages.add(single); + groups.add( + SplitGroup( + partIndex: partIdx, + pageNumbers: [single], + label: 'Part $partIdx: page $single', + suggestedFileName: '${prefix}_page_$single.pdf', + ), + ); + } + partIdx++; + } + + if (groups.isEmpty) { + return const SplitValidationResult( + isValid: false, + errorMessage: 'Enter at least one valid page range.', + ); + } + + if (groups.length > maxOutputFilesCap) { + return SplitValidationResult( + isValid: false, + errorMessage: + 'Custom ranges produce ${groups.length} files (maximum $maxOutputFilesCap allowed).', + exceedsHardCap: true, + ); + } + + // Determine missing pages (pages in 1..totalPages not present in any group) + final missing = []; + for (int p = 1; p <= totalPages; p++) { + if (!includedPages.contains(p)) { + missing.add(p); + } + } + + return SplitValidationResult( + isValid: true, + groups: groups, + missingPages: missing, + requiresCountConfirmation: groups.length > confirmationThreshold, + ); + } +} + +/// On-device Split PDF engine powered by syncfusion_flutter_pdf. +class PdfSplitService { + const PdfSplitService(); + + /// Inspects a PDF file and returns its total page count and whether it is password protected. + Future inspectPdf( + String path, { + String? password, + }) async { + final file = File(path); + if (!await file.exists()) { + throw const FormatException('Selected PDF file does not exist on disk.'); + } + final length = await file.length(); + if (length == 0) { + throw const FormatException('Selected PDF file is empty.'); + } + if (length > AppLimits.maxLocalFileBytes) { + throw FormatException( + 'File exceeds the ${AppLimits.formattedLimitMb} local limit.', + ); + } + + final bytes = await file.readAsBytes(); + return await Isolate.run(() { + sf.PdfDocument? doc; + try { + doc = sf.PdfDocument(inputBytes: bytes, password: password); + return PdfInspectionResult( + pageCount: doc.pages.count, + isEncrypted: false, + ); + } catch (e) { + final msg = e.toString().toLowerCase(); + if (msg.contains('password') || + msg.contains('encrypt') || + msg.contains('security')) { + return const PdfInspectionResult( + pageCount: 0, + isEncrypted: true, + ); + } + throw FormatException('Unable to read PDF file: $e'); + } finally { + doc?.dispose(); + } + }); + } + + /// Splits a PDF document on-device inside a background Isolate. + /// + /// CRITICAL MEMORY GUARANTEE: + /// Processes one output group at a time, immediately saving and disposing + /// each output `PdfDocument` before allocating the next one. + /// Peak memory stays flat ($O(1)$ with respect to total pages/files). + Future splitPdf({ + required String inputPath, + required List groups, + String? password, + String? outputPrefix, + String? outputDirectory, + void Function(String stage, double? progress)? onProgress, + }) async { + if (groups.isEmpty) { + throw ArgumentError('At least one SplitGroup is required.'); + } + if (groups.length > SplitRangeValidator.maxOutputFilesCap) { + throw ArgumentError( + 'Cannot split into more than ${SplitRangeValidator.maxOutputFilesCap} files.', + ); + } + + final file = File(inputPath); + if (!await file.exists()) { + throw const FormatException('Source PDF file does not exist.'); + } + + onProgress?.call('Reading document structure...', 0.05); + final sourceBytes = await file.readAsBytes(); + + final String dirPath; + if (outputDirectory != null && outputDirectory.isNotEmpty) { + dirPath = outputDirectory; + } else { + dirPath = (await getTemporaryDirectory()).path; + } + + final targetDir = Directory(dirPath); + if (!await targetDir.exists()) { + await targetDir.create(recursive: true); + } + + // Convert groups into serializable structure for the Isolate + final serializableGroups = groups.map((g) { + return { + 'partIndex': g.partIndex, + 'pageIndices': g.pageIndices, + 'suggestedFileName': g.suggestedFileName, + }; + }).toList(); + + onProgress?.call('Initializing split engine...', 0.15); + + final timestamp = DateTime.now().millisecondsSinceEpoch; + final payload = await Isolate.run(() { + return _isolateExecuteSplit( + sourceBytes: sourceBytes, + password: password, + dirPath: dirPath, + timestamp: timestamp, + groups: serializableGroups, + ); + }); + + if (payload.containsKey('error')) { + throw FormatException(payload['error'] as String); + } + + final rawOutputs = payload['files'] as List; + final totalSourcePages = payload['totalSourcePages'] as int; + + final outputFiles = rawOutputs.asMap().entries.map((entry) { + final idx = entry.key; + final map = entry.value as Map; + return SplitOutputFile( + partIndex: idx + 1, + outputPath: map['path'] as String, + fileName: map['fileName'] as String, + fileSizeBytes: map['size'] as int, + pageCount: map['pageCount'] as int, + pageNumbers: List.from(map['pageNumbers'] as List), + ); + }).toList(); + + onProgress?.call('Completed', 1.0); + + final sourceFileName = file.uri.pathSegments.last; + return SplitPdfResult( + files: outputFiles, + totalSourcePages: totalSourcePages, + sourceFileName: sourceFileName, + ); + } +} + +/// Standalone top-level Isolate execution function. +Map _isolateExecuteSplit({ + required Uint8List sourceBytes, + required String? password, + required String dirPath, + required int timestamp, + required List> groups, +}) { + sf.PdfDocument? sourceDoc; + try { + sourceDoc = sf.PdfDocument(inputBytes: sourceBytes, password: password); + final totalSourcePages = sourceDoc.pages.count; + final outputList = >[]; + + for (int gIdx = 0; gIdx < groups.length; gIdx++) { + final group = groups[gIdx]; + final pageIndices = List.from(group['pageIndices'] as List); + final suggestedFileName = group['suggestedFileName'] as String; + + // Ensure fileName has .pdf extension + final cleanName = suggestedFileName.toLowerCase().endsWith('.pdf') + ? suggestedFileName + : '$suggestedFileName.pdf'; + + // Disambiguate on-disk filename with unique timestamp + final diskName = '${cleanName.substring(0, cleanName.length - 4)}_${timestamp}_p${gIdx + 1}.pdf'; + final diskPath = '$dirPath/$diskName'; + + // 1. Create target document for this group ONLY + final outDoc = sf.PdfDocument(); + outDoc.pageSettings.margins.all = 0; + + for (final pIdx in pageIndices) { + if (pIdx < 0 || pIdx >= totalSourcePages) { + outDoc.dispose(); + return { + 'error': 'Page index $pIdx is out of bounds (1..$totalSourcePages).', + }; + } + + final sourcePage = sourceDoc.pages[pIdx]; + final template = sourcePage.createTemplate(); + outDoc.pageSettings.size = sourcePage.size; + outDoc.pageSettings.orientation = + sourcePage.size.width > sourcePage.size.height + ? sf.PdfPageOrientation.landscape + : sf.PdfPageOrientation.portrait; + + final targetPage = outDoc.pages.add(); + targetPage.graphics.drawPdfTemplate(template, Offset.zero); + } + + // 2. Save to disk immediately + final outBytes = Uint8List.fromList(outDoc.saveSync()); + File(diskPath).writeAsBytesSync(outBytes); + + // 3. DISPOSE IMMEDIATELY to reclaim all memory buffers + outDoc.dispose(); + + outputList.add({ + 'path': diskPath, + 'fileName': cleanName, + 'size': outBytes.length, + 'pageCount': pageIndices.length, + 'pageNumbers': pageIndices.map((i) => i + 1).toList(), + }); + } + + return { + 'files': outputList, + 'totalSourcePages': totalSourcePages, + }; + } catch (e) { + return {'error': 'Failed during PDF split execution: $e'}; + } finally { + sourceDoc?.dispose(); + } +} diff --git a/lib/services/processing/local_processing_service.dart b/lib/services/processing/local_processing_service.dart index d81834c..91c9741 100644 --- a/lib/services/processing/local_processing_service.dart +++ b/lib/services/processing/local_processing_service.dart @@ -15,6 +15,7 @@ import '../../features/tool_flow/domain/scanned_document.dart'; import '../image_conversion_service.dart'; import '../pdf_compression_service.dart'; import '../pdf_merge_service.dart'; +import '../pdf_split_service.dart'; import 'processing_service.dart'; class LocalProcessingService implements ProcessingService { @@ -121,6 +122,40 @@ class LocalProcessingService implements ProcessingService { } } + if (request.toolId == 'split_pdf') { + try { + if (request.filePaths.isEmpty) { + return const Failure( + ProcessingFailed(reason: 'No input PDF provided for splitting.'), + ); + } + final groups = request.splitGroups; + if (groups == null || groups.isEmpty) { + return const Failure( + ProcessingFailed(reason: 'No split ranges or groups provided.'), + ); + } + const splitter = PdfSplitService(); + final password = request.passwords[request.filePaths.first]; + final result = await splitter.splitPdf( + inputPath: request.filePaths.first, + groups: groups, + password: password, + ); + return Success( + ProcessingResult( + outputFilePath: + result.files.isNotEmpty ? result.files.first.outputPath : '', + outputFilePaths: result.files.map((f) => f.outputPath).toList(), + message: 'Successfully split into ${result.totalFiles} files.', + splitResult: result, + ), + ); + } catch (e) { + return Failure(ProcessingFailed(reason: 'Failed to split PDF: $e')); + } + } + return const Failure( ProcessingFailed(reason: 'Unsupported tool operation.'), ); diff --git a/lib/services/processing/processing_service.dart b/lib/services/processing/processing_service.dart index 0489e66..650aad8 100644 --- a/lib/services/processing/processing_service.dart +++ b/lib/services/processing/processing_service.dart @@ -1,5 +1,6 @@ import '../../core/errors/app_error.dart'; import '../../core/result/result.dart'; +import '../pdf_split_service.dart'; class ProcessingRequest { final String toolId; @@ -7,6 +8,7 @@ class ProcessingRequest { final List filePaths; final Map passwords; final String? outputFileName; + final List? splitGroups; const ProcessingRequest({ required this.toolId, @@ -14,16 +16,21 @@ class ProcessingRequest { this.filePaths = const [], this.passwords = const {}, this.outputFileName, + this.splitGroups, }); } class ProcessingResult { final String outputFilePath; + final List outputFilePaths; final String message; + final SplitPdfResult? splitResult; const ProcessingResult({ required this.outputFilePath, + this.outputFilePaths = const [], this.message = 'Processing completed successfully.', + this.splitResult, }); } diff --git a/test/unit/pdf_split_service_test.dart b/test/unit/pdf_split_service_test.dart new file mode 100644 index 0000000..fad57ad --- /dev/null +++ b/test/unit/pdf_split_service_test.dart @@ -0,0 +1,286 @@ +import 'dart:io'; +import 'dart:ui' show Rect; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:krocpdf/services/pdf_split_service.dart'; +import 'package:syncfusion_flutter_pdf/pdf.dart' as sf; + +Future _createTestPdf( + Directory dir, + String name, { + int pageCount = 1, + String? userPassword, +}) async { + final doc = sf.PdfDocument(); + if (userPassword != null && userPassword.isNotEmpty) { + doc.security.userPassword = userPassword; + doc.security.ownerPassword = '${userPassword}_owner'; + } + final font = sf.PdfStandardFont(sf.PdfFontFamily.helvetica, 14); + for (int i = 0; i < pageCount; i++) { + final page = doc.pages.add(); + page.graphics.drawString( + '$name - Page ${i + 1}', + font, + bounds: const Rect.fromLTWH(40, 40, 400, 100), + ); + } + final bytes = doc.saveSync(); + doc.dispose(); + final file = File('${dir.path}/$name'); + await file.writeAsBytes(bytes); + return file; +} + +void main() { + group('SplitOutputFile metrics', () { + test('formats byte sizes accurately', () { + const small = SplitOutputFile( + outputPath: '/tmp/a.pdf', + fileName: 'a.pdf', + fileSizeBytes: 512, + pageCount: 1, + pageNumbers: [1], + ); + const kb = SplitOutputFile( + outputPath: '/tmp/b.pdf', + fileName: 'b.pdf', + fileSizeBytes: 2048, + pageCount: 2, + pageNumbers: [1, 2], + ); + const mb = SplitOutputFile( + outputPath: '/tmp/c.pdf', + fileName: 'c.pdf', + fileSizeBytes: 2 * 1024 * 1024, + pageCount: 10, + pageNumbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + ); + + expect(small.formattedSize, equals('512 B')); + expect(kb.formattedSize, equals('2.0 KB')); + expect(mb.formattedSize, equals('2.00 MB')); + }); + }); + + group('SplitRangeValidator parsing & validation', () { + test('parses custom ranges correctly', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 10, + customRangesInput: '1-3, 5, 8-10', + prefix: 'Report', + ); + + expect(res.isValid, isTrue); + expect(res.groups.length, equals(3)); + expect(res.groups[0].pageNumbers, equals([1, 2, 3])); + expect(res.groups[0].suggestedFileName, equals('Report_pages_1-3.pdf')); + expect(res.groups[1].pageNumbers, equals([5])); + expect(res.groups[1].suggestedFileName, equals('Report_page_5.pdf')); + expect(res.groups[2].pageNumbers, equals([8, 9, 10])); + expect(res.groups[2].suggestedFileName, equals('Report_pages_8-10.pdf')); + }); + + test('detects gaps and formats omitted pages', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 15, + customRangesInput: '1-3, 10-12', + ); + + expect(res.isValid, isTrue); + expect(res.missingPages, equals([4, 5, 6, 7, 8, 9, 13, 14, 15])); + expect(res.hasSignificantGap, isTrue); + expect(res.formatMissingRanges(), equals('4–9, 13–15')); + }); + + test('does not flag insignificant gaps (1-2 pages omitted)', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 6, + customRangesInput: '1-3, 5-6', + ); + + expect(res.isValid, isTrue); + expect(res.missingPages, equals([4])); + expect(res.hasSignificantGap, isFalse); + }); + + test('rejects out of bounds page numbers', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 5, + customRangesInput: '1-3, 6-8', + ); + + expect(res.isValid, isFalse); + expect(res.errorMessage, contains('exceeds document page count of 5')); + }); + + test('rejects inverted ranges (start > end)', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 10, + customRangesInput: '5-2', + ); + + expect(res.isValid, isFalse); + expect(res.errorMessage, contains('cannot be greater than end page')); + }); + + test('rejects invalid syntax', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 10, + customRangesInput: '1--4', + ); + + expect(res.isValid, isFalse); + expect(res.errorMessage, contains('Invalid range syntax')); + }); + + test('validates Every N Pages splitting with remainder', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.everyNPages, + totalPages: 11, + everyN: 4, + prefix: 'Document', + ); + + expect(res.isValid, isTrue); + expect(res.groups.length, equals(3)); + expect(res.groups[0].pageNumbers, equals([1, 2, 3, 4])); + expect(res.groups[1].pageNumbers, equals([5, 6, 7, 8])); + expect(res.groups[2].pageNumbers, equals([9, 10, 11])); + expect(res.missingPages, isEmpty); + }); + + test('validates Equal Parts splitting with remainder distribution', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.equalParts, + totalPages: 10, + equalParts: 3, + prefix: 'Doc', + ); + + expect(res.isValid, isTrue); + expect(res.groups.length, equals(3)); + expect(res.groups[0].pageNumbers.length, equals(4)); // 10 ~/ 3 + 1 + expect(res.groups[1].pageNumbers.length, equals(3)); + expect(res.groups[2].pageNumbers.length, equals(3)); + expect(res.missingPages, isEmpty); + }); + + test('validates Extract All Pages', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.extractAll, + totalPages: 4, + prefix: 'Doc', + ); + + expect(res.isValid, isTrue); + expect(res.groups.length, equals(4)); + for (int i = 0; i < 4; i++) { + expect(res.groups[i].pageNumbers, equals([i + 1])); + } + }); + + test('enforces 50-file hard cap', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.extractAll, + totalPages: 55, + ); + + expect(res.isValid, isFalse); + expect(res.exceedsHardCap, isTrue); + expect(res.errorMessage, contains('maximum 50 allowed')); + }); + + test('flags 15+ confirmation threshold', () { + final res = SplitRangeValidator.validate( + mode: SplitMode.extractAll, + totalPages: 20, + ); + + expect(res.isValid, isTrue); + expect(res.requiresCountConfirmation, isTrue); + }); + }); + + group('PdfSplitService execution & integrity', () { + late Directory tempDir; + + setUp(() { + tempDir = Directory.systemTemp.createTempSync('kroc_split_test_'); + }); + + tearDown(() { + if (tempDir.existsSync()) { + tempDir.deleteSync(recursive: true); + } + }); + + test('splits PDF using custom ranges and verifies output integrity', () async { + final pdf = await _createTestPdf(tempDir, 'sample.pdf', pageCount: 8); + const service = PdfSplitService(); + + final validation = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 8, + customRangesInput: '1-3, 5, 7-8', + prefix: 'custom_split', + ); + + final stages = []; + final result = await service.splitPdf( + inputPath: pdf.path, + groups: validation.groups, + outputDirectory: tempDir.path, + onProgress: (stage, _) => stages.add(stage), + ); + + expect(result.files.length, equals(3)); + expect(result.totalSourcePages, equals(8)); + expect(stages.isNotEmpty, isTrue); + + // Part 1: pages 1-3 + final doc1 = sf.PdfDocument(inputBytes: File(result.files[0].outputPath).readAsBytesSync()); + expect(doc1.pages.count, equals(3)); + doc1.dispose(); + + // Part 2: page 5 + final doc2 = sf.PdfDocument(inputBytes: File(result.files[1].outputPath).readAsBytesSync()); + expect(doc2.pages.count, equals(1)); + doc2.dispose(); + + // Part 3: pages 7-8 + final doc3 = sf.PdfDocument(inputBytes: File(result.files[2].outputPath).readAsBytesSync()); + expect(doc3.pages.count, equals(2)); + doc3.dispose(); + }); + + test('inspectPdf correctly identifies pages and encryption', () async { + final unencrypted = await _createTestPdf(tempDir, 'plain.pdf', pageCount: 4); + final encrypted = await _createTestPdf( + tempDir, + 'secret.pdf', + pageCount: 3, + userPassword: 'pass', + ); + + const service = PdfSplitService(); + + final res1 = await service.inspectPdf(unencrypted.path); + expect(res1.pageCount, equals(4)); + expect(res1.isEncrypted, isFalse); + + final res2 = await service.inspectPdf(encrypted.path); + expect(res2.isEncrypted, isTrue); + + final res3 = await service.inspectPdf(encrypted.path, password: 'pass'); + expect(res3.pageCount, equals(3)); + expect(res3.isEncrypted, isFalse); + }); + }); +} From 0967a653149716594c810183eb52b2d04c046ab6 Mon Sep 17 00:00:00 2001 From: Mayank37408 Date: Fri, 13 Nov 2026 14:30:44 +0530 Subject: [PATCH 2/2] fix(split-pdf): wrap control flow statements in braces and update CHANGELOG for release notes gate --- CHANGELOG.md | 1 + .../presentation/tool_flow_screen.dart | 261 ++++++++++-------- lib/services/pdf_split_service.dart | 89 +++--- .../processing/local_processing_service.dart | 5 +- test/unit/pdf_split_service_test.dart | 91 +++--- 5 files changed, 250 insertions(+), 197 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d0ce377..49a8513 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- On-device Split PDF engine (`PdfSplitService`) with 4 splitting modes (custom page ranges, every N pages, extract all pages, split into N parts), memory-safe isolate execution, page boundary/gap validation, and complete `ToolFlowScreen` integration (#23, #40). - On-device two-PDF merge engine (`PdfMergeService`) using `syncfusion_flutter_pdf` inside `Isolate.run()` with unified 1-or-2-file password prompt (`showPdfPasswordDialog`) and full `ToolFlowScreen` integration (#22). - Branded launch animation sequence (`LaunchAnimationScreen` and `LaunchGate`) featuring paper drop, conversion to PDF document, crocodile bite interaction, carrier motion, and trail reveal into the KrocPDF wordmark. - Wall-clock monotonic `Stopwatch` + `Ticker` timing engine ensuring a consistent 4.2-second launch pacing across all display refresh rates (60Hz, 90Hz, 120Hz). diff --git a/lib/features/tool_flow/presentation/tool_flow_screen.dart b/lib/features/tool_flow/presentation/tool_flow_screen.dart index 388c1a6..d1dfdc6 100644 --- a/lib/features/tool_flow/presentation/tool_flow_screen.dart +++ b/lib/features/tool_flow/presentation/tool_flow_screen.dart @@ -92,15 +92,18 @@ class _ToolFlowScreenState extends ConsumerState { final PdfSplitService _splitService = const PdfSplitService(); final TextEditingController _splitPrefixController = TextEditingController(); final TextEditingController _splitRangesController = TextEditingController(); - final TextEditingController _splitEveryNController = - TextEditingController(text: '2'); - final TextEditingController _splitPartsController = - TextEditingController(text: '2'); + final TextEditingController _splitEveryNController = TextEditingController( + text: '2', + ); + final TextEditingController _splitPartsController = TextEditingController( + text: '2', + ); SplitMode _splitMode = SplitMode.customRanges; int _splitTotalPages = 1; bool _splitIsEncrypted = false; - SplitValidationResult _splitValidation = - const SplitValidationResult(isValid: false); + SplitValidationResult _splitValidation = const SplitValidationResult( + isValid: false, + ); bool _isSplitting = false; String _splitStage = ''; double? _splitProgress; @@ -1119,8 +1122,9 @@ class _ToolFlowScreenState extends ConsumerState { if (mounted) { setState(() { - _splitTotalPages = - inspection.pageCount > 0 ? inspection.pageCount : 1; + _splitTotalPages = inspection.pageCount > 0 + ? inspection.pageCount + : 1; _splitIsEncrypted = inspection.isEncrypted; if (_splitPrefixController.text.isEmpty) { _splitPrefixController.text = baseName; @@ -1174,7 +1178,9 @@ class _ToolFlowScreenState extends ConsumerState { } Future _promptOrStartSplit() async { - if (!_splitValidation.isValid || _selectedFiles.isEmpty) return; + if (!_splitValidation.isValid || _selectedFiles.isEmpty) { + return; + } // 1. Check for 15+ files warning if (_splitValidation.fileCount >= 15) { @@ -1197,8 +1203,12 @@ class _ToolFlowScreenState extends ConsumerState { ], ), ); - if (proceed != true) return; - if (!mounted) return; + if (proceed != true) { + return; + } + if (!mounted) { + return; + } } // 2. Check for gap confirmation (> 2 omitted pages in customRanges) @@ -1224,15 +1234,21 @@ class _ToolFlowScreenState extends ConsumerState { ], ), ); - if (proceed != true) return; - if (!mounted) return; + if (proceed != true) { + return; + } + if (!mounted) { + return; + } } _startSplit(); } Future _startSplit() async { - if (_selectedFiles.isEmpty || _isSplitting) return; + if (_selectedFiles.isEmpty || _isSplitting) { + return; + } final file = _selectedFiles.first; if (!await file.exists()) { @@ -1298,11 +1314,13 @@ class _ToolFlowScreenState extends ConsumerState { for (final out in _splitResult!.outputFiles) { final f = File(out.outputPath); if (await f.exists()) { - await ref.read(savedFilesProvider.notifier).addExternalFile( - f, - customTitle: out.fileName, - sourceType: SavedDocumentSource.split, - ); + await ref + .read(savedFilesProvider.notifier) + .addExternalFile( + f, + customTitle: out.fileName, + sourceType: SavedDocumentSource.split, + ); savedCount++; } } @@ -1332,9 +1350,12 @@ class _ToolFlowScreenState extends ConsumerState { } Future _handleShareAllSplitPdfs() async { - if (_splitResult == null || _splitResult!.outputFiles.isEmpty) return; - final xfiles = - _splitResult!.outputFiles.map((f) => XFile(f.outputPath)).toList(); + if (_splitResult == null || _splitResult!.outputFiles.isEmpty) { + return; + } + final xfiles = _splitResult!.outputFiles + .map((f) => XFile(f.outputPath)) + .toList(); // ignore: deprecated_member_use await Share.shareXFiles(xfiles); } @@ -1403,7 +1424,12 @@ class _ToolFlowScreenState extends ConsumerState { return Expanded( child: InkWell( onTap: () { - if (_isConverting || _isCompressing || _isMerging || _isSplitting) return; + if (_isConverting || + _isCompressing || + _isMerging || + _isSplitting) { + return; + } if (_isImageConvert) { if (index == 0) { setState(() => _currentStepIndex = index); @@ -1504,7 +1530,11 @@ class _ToolFlowScreenState extends ConsumerState { ? _buildSplitPdfResultStep(context, borderColor, isDark) : Center( child: SingleChildScrollView( - child: _buildStepContent(context, borderColor, isDark), + child: _buildStepContent( + context, + borderColor, + isDark, + ), ), ), ), @@ -1515,77 +1545,82 @@ class _ToolFlowScreenState extends ConsumerState { Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( - border: Border(top: BorderSide(color: borderColor, width: 1)), + border: Border( + top: BorderSide(color: borderColor, width: 1), + ), ), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - if (_currentStepIndex > 0 && - !_isConverting && - !_isCompressing && - !_isMerging && - !_isSplitting) - OutlinedButton( - onPressed: () => setState(() => _currentStepIndex--), - child: const Text('Back'), - ) - else - const SizedBox.shrink(), - if (_currentStepIndex < _steps.length - 1) - ElevatedButton( - onPressed: canGoNext - ? () { - if (_isImageConvert && _currentStepIndex == 1) { - _startConversion(); - } else if (_isCompressPdf && - _currentStepIndex == 1) { - _startCompression(); - } else if (_isMergePdf && - _currentStepIndex == 1) { - _startMerge(); - } else if (_isSplitPdf && - _currentStepIndex == 1) { - _promptOrStartSplit(); - } else { - setState(() { - _currentStepIndex++; - if (_isSplitPdf && - _currentStepIndex == 1 && - _selectedFiles.isNotEmpty) { - _inspectAndInitSplit(_selectedFiles.first); - } - }); + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + if (_currentStepIndex > 0 && + !_isConverting && + !_isCompressing && + !_isMerging && + !_isSplitting) + OutlinedButton( + onPressed: () => setState(() => _currentStepIndex--), + child: const Text('Back'), + ) + else + const SizedBox.shrink(), + if (_currentStepIndex < _steps.length - 1) + ElevatedButton( + onPressed: canGoNext + ? () { + if (_isImageConvert && + _currentStepIndex == 1) { + _startConversion(); + } else if (_isCompressPdf && + _currentStepIndex == 1) { + _startCompression(); + } else if (_isMergePdf && + _currentStepIndex == 1) { + _startMerge(); + } else if (_isSplitPdf && + _currentStepIndex == 1) { + _promptOrStartSplit(); + } else { + setState(() { + _currentStepIndex++; + if (_isSplitPdf && + _currentStepIndex == 1 && + _selectedFiles.isNotEmpty) { + _inspectAndInitSplit( + _selectedFiles.first, + ); + } + }); + } } - } - : null, - child: Text( - _isImageConvert && _currentStepIndex == 1 - ? 'Convert to $_targetFormat' - : _isCompressPdf && _currentStepIndex == 1 - ? 'Compress PDF' - : _isMergePdf && _currentStepIndex == 1 - ? 'Merge PDF' - : _isSplitPdf && _currentStepIndex == 1 - ? 'Split PDF' - : 'Next step', - ), - ) - else - ElevatedButton( - onPressed: _resetFlow, - child: Text( - _isCompressPdf - ? 'Compress another' - : _isMergePdf - ? 'Merge another' - : _isSplitPdf - ? 'Split another' - : 'Convert another', + : null, + child: Text( + _isImageConvert && _currentStepIndex == 1 + ? 'Convert to $_targetFormat' + : _isCompressPdf && _currentStepIndex == 1 + ? 'Compress PDF' + : _isMergePdf && _currentStepIndex == 1 + ? 'Merge PDF' + : _isSplitPdf && _currentStepIndex == 1 + ? 'Split PDF' + : 'Next step', + ), + ) + else + ElevatedButton( + onPressed: _resetFlow, + child: Text( + _isCompressPdf + ? 'Compress another' + : _isMergePdf + ? 'Merge another' + : _isSplitPdf + ? 'Split another' + : 'Convert another', + ), ), - ), - ], + ], + ), ), - ), ], ), ), @@ -2941,8 +2976,12 @@ class _ToolFlowScreenState extends ConsumerState { // --- Compress PDF Specific Steps --- String _getQualityDescriptor(int q) { - if (q <= 40) return '(Smallest Size)'; - if (q <= 70) return '(Balanced)'; + if (q <= 40) { + return '(Smallest Size)'; + } + if (q <= 70) { + return '(Balanced)'; + } return '(High Quality)'; } @@ -4037,7 +4076,9 @@ class _ToolFlowScreenState extends ConsumerState { Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( - color: isDark ? const Color(0xFF1F1F1F) : const Color(0xFFF0F0F0), + color: isDark + ? const Color(0xFF1F1F1F) + : const Color(0xFFF0F0F0), borderRadius: BorderRadius.circular(6), ), child: Row( @@ -4154,8 +4195,8 @@ class _ToolFlowScreenState extends ConsumerState { color: !_splitValidation.isValid ? Colors.red.shade400 : (_splitValidation.hasSignificantGap - ? Colors.amber.shade600 - : borderColor), + ? Colors.amber.shade600 + : borderColor), width: 1, ), borderRadius: BorderRadius.circular(8), @@ -4169,14 +4210,14 @@ class _ToolFlowScreenState extends ConsumerState { !_splitValidation.isValid ? Icons.error_outline : (_splitValidation.hasSignificantGap - ? Icons.warning_amber_rounded - : Icons.preview_outlined), + ? Icons.warning_amber_rounded + : Icons.preview_outlined), size: 20, color: !_splitValidation.isValid ? Colors.red : (_splitValidation.hasSignificantGap - ? Colors.amber.shade700 - : const Color(0xFF007AFF)), + ? Colors.amber.shade700 + : const Color(0xFF007AFF)), ), const SizedBox(width: 8), const Text( @@ -4194,7 +4235,9 @@ class _ToolFlowScreenState extends ConsumerState { vertical: 2, ), decoration: BoxDecoration( - color: const Color(0xFF007AFF).withValues(alpha: 0.15), + color: const Color( + 0xFF007AFF, + ).withValues(alpha: 0.15), borderRadius: BorderRadius.circular(10), ), child: Text( @@ -4474,8 +4517,9 @@ class _ToolFlowScreenState extends ConsumerState { } final fileCount = res.outputFiles.length; - final fileCountText = - fileCount == 1 ? '1 PDF file' : '$fileCount PDF files'; + final fileCountText = fileCount == 1 + ? '1 PDF file' + : '$fileCount PDF files'; return Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -4685,15 +4729,17 @@ class _ToolFlowScreenState extends ConsumerState { ? null : _handleSaveAllSplitPdfs, icon: Icon( - _isSplitSavedToFiles ? Icons.check : Icons.save_alt_outlined, + _isSplitSavedToFiles + ? Icons.check + : Icons.save_alt_outlined, size: 16, ), label: Text( _isSavingSplitPdf ? 'Saving...' : (_isSplitSavedToFiles - ? 'Saved All' - : 'Save All to Files'), + ? 'Saved All' + : 'Save All to Files'), ), ), ), @@ -4707,10 +4753,7 @@ class _ToolFlowScreenState extends ConsumerState { ), ), const SizedBox(width: 8), - OutlinedButton( - onPressed: _resetFlow, - child: const Text('Done'), - ), + OutlinedButton(onPressed: _resetFlow, child: const Text('Done')), ], ), ), diff --git a/lib/services/pdf_split_service.dart b/lib/services/pdf_split_service.dart index f6de3b2..bcb877c 100644 --- a/lib/services/pdf_split_service.dart +++ b/lib/services/pdf_split_service.dart @@ -50,8 +50,8 @@ class SplitGroup { String get rangeString => pageNumbers.isEmpty ? '' : (pageNumbers.length == 1 - ? '${pageNumbers.first}' - : '${pageNumbers.first}–${pageNumbers.last}'); + ? '${pageNumbers.first}' + : '${pageNumbers.first}–${pageNumbers.last}'); /// Returns 0-based page indices for internal PDF page operations. List get pageIndices => pageNumbers.map((p) => p - 1).toList(); @@ -84,7 +84,9 @@ class SplitValidationResult { /// Formats missing pages into friendly range strings (e.g. "4-7, 10"). String formatMissingRanges() { - if (missingPages.isEmpty) return ''; + if (missingPages.isEmpty) { + return ''; + } final ranges = []; int? rangeStart; int? prev; @@ -129,8 +131,8 @@ class SplitOutputFile { String get sourceRange => pageNumbers.isEmpty ? '' : (pageNumbers.length == 1 - ? '${pageNumbers.first}' - : '${pageNumbers.first}–${pageNumbers.last}'); + ? '${pageNumbers.first}' + : '${pageNumbers.first}–${pageNumbers.last}'); String get formattedSize { if (fileSizeBytes < 1024) { @@ -169,47 +171,43 @@ class SplitRangeValidator { String input, int totalPages, { String prefix = 'document', - }) => - validate( - mode: SplitMode.customRanges, - totalPages: totalPages, - customRangesInput: input, - prefix: prefix, - ); + }) => validate( + mode: SplitMode.customRanges, + totalPages: totalPages, + customRangesInput: input, + prefix: prefix, + ); static SplitValidationResult validateEveryNPages( int n, int totalPages, { String prefix = 'document', - }) => - validate( - mode: SplitMode.everyNPages, - totalPages: totalPages, - everyN: n, - prefix: prefix, - ); + }) => validate( + mode: SplitMode.everyNPages, + totalPages: totalPages, + everyN: n, + prefix: prefix, + ); static SplitValidationResult validateExtractAllPages( int totalPages, { String prefix = 'document', - }) => - validate( - mode: SplitMode.extractAll, - totalPages: totalPages, - prefix: prefix, - ); + }) => validate( + mode: SplitMode.extractAll, + totalPages: totalPages, + prefix: prefix, + ); static SplitValidationResult validateSplitIntoNParts( int parts, int totalPages, { String prefix = 'document', - }) => - validate( - mode: SplitMode.equalParts, - totalPages: totalPages, - equalParts: parts, - prefix: prefix, - ); + }) => validate( + mode: SplitMode.equalParts, + totalPages: totalPages, + equalParts: parts, + prefix: prefix, + ); /// Parses and validates page ranges for any of the 4 Split modes. static SplitValidationResult validate({ @@ -381,8 +379,7 @@ class SplitRangeValidator { partIndex: i + 1, pageNumbers: pages, label: 'Part ${i + 1}: pages $rangeStr', - suggestedFileName: - '${prefix}_part${i + 1}_pages_$fileRangeStr.pdf', + suggestedFileName: '${prefix}_part${i + 1}_pages_$fileRangeStr.pdf', ), ); currentStart = currentEnd + 1; @@ -416,7 +413,9 @@ class SplitRangeValidator { for (final seg in segments) { final s = seg.trim(); - if (s.isEmpty) continue; + if (s.isEmpty) { + continue; + } if (s.contains('-')) { final parts = s.split('-'); @@ -578,10 +577,7 @@ class PdfSplitService { if (msg.contains('password') || msg.contains('encrypt') || msg.contains('security')) { - return const PdfInspectionResult( - pageCount: 0, - isEncrypted: true, - ); + return const PdfInspectionResult(pageCount: 0, isEncrypted: true); } throw FormatException('Unable to read PDF file: $e'); } finally { @@ -711,7 +707,8 @@ Map _isolateExecuteSplit({ : '$suggestedFileName.pdf'; // Disambiguate on-disk filename with unique timestamp - final diskName = '${cleanName.substring(0, cleanName.length - 4)}_${timestamp}_p${gIdx + 1}.pdf'; + final diskName = + '${cleanName.substring(0, cleanName.length - 4)}_${timestamp}_p${gIdx + 1}.pdf'; final diskPath = '$dirPath/$diskName'; // 1. Create target document for this group ONLY @@ -722,7 +719,8 @@ Map _isolateExecuteSplit({ if (pIdx < 0 || pIdx >= totalSourcePages) { outDoc.dispose(); return { - 'error': 'Page index $pIdx is out of bounds (1..$totalSourcePages).', + 'error': + 'Page index $pIdx is out of bounds (1..$totalSourcePages).', }; } @@ -731,8 +729,8 @@ Map _isolateExecuteSplit({ outDoc.pageSettings.size = sourcePage.size; outDoc.pageSettings.orientation = sourcePage.size.width > sourcePage.size.height - ? sf.PdfPageOrientation.landscape - : sf.PdfPageOrientation.portrait; + ? sf.PdfPageOrientation.landscape + : sf.PdfPageOrientation.portrait; final targetPage = outDoc.pages.add(); targetPage.graphics.drawPdfTemplate(template, Offset.zero); @@ -754,10 +752,7 @@ Map _isolateExecuteSplit({ }); } - return { - 'files': outputList, - 'totalSourcePages': totalSourcePages, - }; + return {'files': outputList, 'totalSourcePages': totalSourcePages}; } catch (e) { return {'error': 'Failed during PDF split execution: $e'}; } finally { diff --git a/lib/services/processing/local_processing_service.dart b/lib/services/processing/local_processing_service.dart index 91c9741..7675cca 100644 --- a/lib/services/processing/local_processing_service.dart +++ b/lib/services/processing/local_processing_service.dart @@ -144,8 +144,9 @@ class LocalProcessingService implements ProcessingService { ); return Success( ProcessingResult( - outputFilePath: - result.files.isNotEmpty ? result.files.first.outputPath : '', + outputFilePath: result.files.isNotEmpty + ? result.files.first.outputPath + : '', outputFilePaths: result.files.map((f) => f.outputPath).toList(), message: 'Successfully split into ${result.totalFiles} files.', splitResult: result, diff --git a/test/unit/pdf_split_service_test.dart b/test/unit/pdf_split_service_test.dart index fad57ad..75be9f2 100644 --- a/test/unit/pdf_split_service_test.dart +++ b/test/unit/pdf_split_service_test.dart @@ -221,47 +221,60 @@ void main() { } }); - test('splits PDF using custom ranges and verifies output integrity', () async { - final pdf = await _createTestPdf(tempDir, 'sample.pdf', pageCount: 8); - const service = PdfSplitService(); - - final validation = SplitRangeValidator.validate( - mode: SplitMode.customRanges, - totalPages: 8, - customRangesInput: '1-3, 5, 7-8', - prefix: 'custom_split', - ); - - final stages = []; - final result = await service.splitPdf( - inputPath: pdf.path, - groups: validation.groups, - outputDirectory: tempDir.path, - onProgress: (stage, _) => stages.add(stage), - ); - - expect(result.files.length, equals(3)); - expect(result.totalSourcePages, equals(8)); - expect(stages.isNotEmpty, isTrue); - - // Part 1: pages 1-3 - final doc1 = sf.PdfDocument(inputBytes: File(result.files[0].outputPath).readAsBytesSync()); - expect(doc1.pages.count, equals(3)); - doc1.dispose(); - - // Part 2: page 5 - final doc2 = sf.PdfDocument(inputBytes: File(result.files[1].outputPath).readAsBytesSync()); - expect(doc2.pages.count, equals(1)); - doc2.dispose(); - - // Part 3: pages 7-8 - final doc3 = sf.PdfDocument(inputBytes: File(result.files[2].outputPath).readAsBytesSync()); - expect(doc3.pages.count, equals(2)); - doc3.dispose(); - }); + test( + 'splits PDF using custom ranges and verifies output integrity', + () async { + final pdf = await _createTestPdf(tempDir, 'sample.pdf', pageCount: 8); + const service = PdfSplitService(); + + final validation = SplitRangeValidator.validate( + mode: SplitMode.customRanges, + totalPages: 8, + customRangesInput: '1-3, 5, 7-8', + prefix: 'custom_split', + ); + + final stages = []; + final result = await service.splitPdf( + inputPath: pdf.path, + groups: validation.groups, + outputDirectory: tempDir.path, + onProgress: (stage, _) => stages.add(stage), + ); + + expect(result.files.length, equals(3)); + expect(result.totalSourcePages, equals(8)); + expect(stages.isNotEmpty, isTrue); + + // Part 1: pages 1-3 + final doc1 = sf.PdfDocument( + inputBytes: File(result.files[0].outputPath).readAsBytesSync(), + ); + expect(doc1.pages.count, equals(3)); + doc1.dispose(); + + // Part 2: page 5 + final doc2 = sf.PdfDocument( + inputBytes: File(result.files[1].outputPath).readAsBytesSync(), + ); + expect(doc2.pages.count, equals(1)); + doc2.dispose(); + + // Part 3: pages 7-8 + final doc3 = sf.PdfDocument( + inputBytes: File(result.files[2].outputPath).readAsBytesSync(), + ); + expect(doc3.pages.count, equals(2)); + doc3.dispose(); + }, + ); test('inspectPdf correctly identifies pages and encryption', () async { - final unencrypted = await _createTestPdf(tempDir, 'plain.pdf', pageCount: 4); + final unencrypted = await _createTestPdf( + tempDir, + 'plain.pdf', + pageCount: 4, + ); final encrypted = await _createTestPdf( tempDir, 'secret.pdf',