generated from dellevin/template
新增阅读器功能,待优化
This commit is contained in:
@@ -35,12 +35,8 @@ Future<void> _bootstrap(AppProvider appProvider) async {
|
||||
}
|
||||
appProvider.initMainTabIndex();
|
||||
|
||||
// sync 校验在数据库加载完成后执行(避免阻塞本地数据展示)
|
||||
try {
|
||||
await _validateSyncOnStartup();
|
||||
} catch (e) {
|
||||
debugPrint('[Startup] 同步状态校验失败: $e');
|
||||
}
|
||||
// sync 校验放到后台执行,不阻塞启动
|
||||
unawaited(_validateSyncOnStartup());
|
||||
|
||||
unawaited(_initAutoBackup());
|
||||
unawaited(_initUsageStats());
|
||||
|
||||
104
lib/models/reader_book.dart
Normal file
104
lib/models/reader_book.dart
Normal file
@@ -0,0 +1,104 @@
|
||||
/// 阅读器书籍模型
|
||||
class ReaderBook {
|
||||
final String id;
|
||||
final String title;
|
||||
final String author;
|
||||
final String? coverPath;
|
||||
final String filePath; // 相对路径
|
||||
final String fileName;
|
||||
final String fileExtension;
|
||||
final String lastReadCfi;
|
||||
final double readingPercentage;
|
||||
final DateTime createdAt;
|
||||
final DateTime updatedAt;
|
||||
final bool isDeleted;
|
||||
|
||||
ReaderBook({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.author = '',
|
||||
this.coverPath,
|
||||
required this.filePath,
|
||||
required this.fileName,
|
||||
required this.fileExtension,
|
||||
this.lastReadCfi = '',
|
||||
this.readingPercentage = 0.0,
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
this.isDeleted = false,
|
||||
});
|
||||
|
||||
factory ReaderBook.fromJson(Map<String, dynamic> json) {
|
||||
return ReaderBook(
|
||||
id: json['id'] ?? '',
|
||||
title: json['title'] ?? '',
|
||||
author: json['author'] ?? '',
|
||||
coverPath: json['cover_path'],
|
||||
filePath: json['file_path'] ?? '',
|
||||
fileName: json['file_name'] ?? '',
|
||||
fileExtension: json['file_extension'] ?? 'epub',
|
||||
lastReadCfi: json['last_read_cfi'] ?? '',
|
||||
readingPercentage: (json['reading_percentage'] as num?)?.toDouble() ?? 0.0,
|
||||
createdAt: json['created_at'] != null
|
||||
? DateTime.parse(json['created_at'])
|
||||
: DateTime.now(),
|
||||
updatedAt: json['updated_at'] != null
|
||||
? DateTime.parse(json['updated_at'])
|
||||
: DateTime.now(),
|
||||
isDeleted: json['is_deleted'] == 1 || json['is_deleted'] == true,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'title': title,
|
||||
'author': author,
|
||||
'cover_path': coverPath,
|
||||
'file_path': filePath,
|
||||
'file_name': fileName,
|
||||
'file_extension': fileExtension,
|
||||
'last_read_cfi': lastReadCfi,
|
||||
'reading_percentage': readingPercentage,
|
||||
'created_at': createdAt.toUtc().toIso8601String(),
|
||||
'updated_at': updatedAt.toUtc().toIso8601String(),
|
||||
'is_deleted': isDeleted ? 1 : 0,
|
||||
};
|
||||
}
|
||||
|
||||
ReaderBook copyWith({
|
||||
String? id,
|
||||
String? title,
|
||||
String? author,
|
||||
Object? coverPath = _readerBookCopyWithNull,
|
||||
String? filePath,
|
||||
String? fileName,
|
||||
String? fileExtension,
|
||||
String? lastReadCfi,
|
||||
double? readingPercentage,
|
||||
DateTime? createdAt,
|
||||
DateTime? updatedAt,
|
||||
bool? isDeleted,
|
||||
}) {
|
||||
return ReaderBook(
|
||||
id: id ?? this.id,
|
||||
title: title ?? this.title,
|
||||
author: author ?? this.author,
|
||||
coverPath: coverPath is _ReaderBookCopyWithNullSentinel ? this.coverPath : (coverPath as String?),
|
||||
filePath: filePath ?? this.filePath,
|
||||
fileName: fileName ?? this.fileName,
|
||||
fileExtension: fileExtension ?? this.fileExtension,
|
||||
lastReadCfi: lastReadCfi ?? this.lastReadCfi,
|
||||
readingPercentage: readingPercentage ?? this.readingPercentage,
|
||||
createdAt: createdAt ?? this.createdAt,
|
||||
updatedAt: updatedAt ?? this.updatedAt,
|
||||
isDeleted: isDeleted ?? this.isDeleted,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReaderBookCopyWithNullSentinel {
|
||||
const _ReaderBookCopyWithNullSentinel();
|
||||
}
|
||||
|
||||
const _readerBookCopyWithNull = _ReaderBookCopyWithNullSentinel();
|
||||
@@ -29,6 +29,7 @@ class _BookTabPageState extends State<BookTabPage> {
|
||||
DateTime? _lastUpdatedAt;
|
||||
late ScrollController _scrollController;
|
||||
AppProvider? _provider;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
static const _statusMap = {0: 'read', 1: 'reading', 2: 'want_to_read'};
|
||||
|
||||
@@ -57,6 +58,15 @@ class _BookTabPageState extends State<BookTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.books.length;
|
||||
final latest = provider.books.isNotEmpty ? provider.books.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
@@ -26,7 +26,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
bool _showNoteTab = true;
|
||||
|
||||
late PageController _pageController;
|
||||
bool _isTabTap = false; // 防止点击 Tab 和滑动互斥
|
||||
bool _isTabTap = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -82,6 +82,8 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
// ─── AppBar ──────────────────────────────────────────
|
||||
|
||||
Widget _buildAppBar(BuildContext context) {
|
||||
return Consumer<AppProvider>(
|
||||
builder: (context, provider, child) {
|
||||
@@ -99,6 +101,17 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
String _getAppBarTitle(AppProvider provider) {
|
||||
switch (provider.mainTabIndex) {
|
||||
case 0: return '影视';
|
||||
case 1: return '阅读';
|
||||
case 2: return '笔记';
|
||||
default: return 'MookNote';
|
||||
}
|
||||
}
|
||||
|
||||
// ─── 云备份 ──────────────────────────────────────────
|
||||
|
||||
Widget _buildCloudSyncButton(BuildContext context) {
|
||||
return IconButton(
|
||||
icon: const Icon(Icons.cloud_sync_outlined),
|
||||
@@ -110,7 +123,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
void _showCloudSheet(BuildContext context) async {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final hasConfig = (await WebDAVService.instance.getConfig()) != null;
|
||||
|
||||
if (!mounted) return;
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -220,18 +232,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
]),
|
||||
);
|
||||
|
||||
String _getAppBarTitle(AppProvider provider) {
|
||||
switch (provider.mainTabIndex) {
|
||||
case 0: return '影视';
|
||||
case 1: return '阅读';
|
||||
case 2: return '笔记';
|
||||
default: return 'MookNote';
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// Tab 栏 + 指示条(跟随 PageView 滑动)
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// ─── Tab 栏 + 指示条 ─────────────────────────────────
|
||||
|
||||
Widget _buildTabBar(BuildContext context) {
|
||||
return Consumer<AppProvider>(
|
||||
@@ -273,7 +274,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
}).toList(),
|
||||
),
|
||||
),
|
||||
// 指示条 — 跟随 PageView 滑动
|
||||
AnimatedBuilder(
|
||||
animation: _pageController,
|
||||
builder: (context, _) {
|
||||
@@ -302,9 +302,7 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// PageView 内容区
|
||||
// ═══════════════════════════════════════════════════════════════════
|
||||
// ─── PageView 内容区 ─────────────────────────────────
|
||||
|
||||
Widget _buildTabContent() {
|
||||
return Consumer<AppProvider>(
|
||||
@@ -312,7 +310,6 @@ class _MainContentPageState extends State<MainContentPage> {
|
||||
final tabs = _enabledTabs;
|
||||
final safeIndex = _mapToEnabledTabIndex(provider.mainTabIndex).clamp(0, tabs.length - 1);
|
||||
|
||||
// 同步 provider → PageView(点击 Tab 触发)
|
||||
if (_isTabTap && _pageController.hasClients) {
|
||||
_pageController.animateToPage(safeIndex, duration: const Duration(milliseconds: 350), curve: Curves.easeInOut);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ class _MovieTabPageState extends State<MovieTabPage> {
|
||||
DateTime? _lastUpdatedAt;
|
||||
late ScrollController _scrollController;
|
||||
AppProvider? _provider;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
static const _statusMap = {0: 'watched', 1: 'watching', 2: 'want_to_watch'};
|
||||
|
||||
@@ -57,6 +58,15 @@ class _MovieTabPageState extends State<MovieTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.movies.length;
|
||||
final latest = provider.movies.isNotEmpty ? provider.movies.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
@@ -26,6 +26,7 @@ class _NoteTabPageState extends State<NoteTabPage> {
|
||||
bool _initialized = false;
|
||||
int _lastDataCount = -1;
|
||||
DateTime? _lastUpdatedAt;
|
||||
int _lastScrollSignal = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -52,6 +53,15 @@ class _NoteTabPageState extends State<NoteTabPage> {
|
||||
void _onDataChanged() {
|
||||
if (!_initialized || !mounted) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
|
||||
// 检查回到顶部信号
|
||||
if (provider.scrollToTopSignal != _lastScrollSignal && provider.scrollToTopSignal > 0) {
|
||||
_lastScrollSignal = provider.scrollToTopSignal;
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(0, duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
}
|
||||
}
|
||||
|
||||
final count = provider.notes.length;
|
||||
final latest = provider.notes.isNotEmpty ? provider.notes.first.updatedAt : null;
|
||||
if (count != _lastDataCount || latest != _lastUpdatedAt) {
|
||||
|
||||
182
lib/pages/reader/bookshelf_page.dart
Normal file
182
lib/pages/reader/bookshelf_page.dart
Normal file
@@ -0,0 +1,182 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../service/book_import_service.dart';
|
||||
import 'reader_book_detail_page.dart';
|
||||
|
||||
/// 书架页面 — 展示导入的阅读器书籍,支持网格/列表切换
|
||||
class BookshelfPage extends StatefulWidget {
|
||||
const BookshelfPage({super.key});
|
||||
|
||||
@override
|
||||
State<BookshelfPage> createState() => _BookshelfPageState();
|
||||
}
|
||||
|
||||
class _BookshelfPageState extends State<BookshelfPage> {
|
||||
bool _isGridView = true;
|
||||
|
||||
Future<void> _importBook() async {
|
||||
final provider = context.read<AppProvider>();
|
||||
await BookImportService.pickAndImportBook(context, provider);
|
||||
}
|
||||
|
||||
void _openBookDetail(ReaderBook book) {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ReaderBookDetailPage(book: book),
|
||||
),
|
||||
).then((_) {
|
||||
context.read<AppProvider>().loadReaderBooks();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colors.surface,
|
||||
appBar: AppBar(
|
||||
title: const Text('阅读器'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: Icon(_isGridView ? Icons.view_list : Icons.grid_view),
|
||||
tooltip: _isGridView ? '列表视图' : '网格视图',
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isGridView = !_isGridView;
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add),
|
||||
tooltip: '导入书籍',
|
||||
onPressed: _importBook,
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Consumer<AppProvider>(
|
||||
builder: (context, provider, child) {
|
||||
final books = provider.readerBooks;
|
||||
|
||||
if (books.isEmpty) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.menu_book_outlined, size: 64, color: colors.onSurface.withValues(alpha: 0.15)),
|
||||
const SizedBox(height: 16),
|
||||
Text('点击右上角导入书籍',
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (_isGridView) {
|
||||
return GridView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 3,
|
||||
mainAxisSpacing: 16,
|
||||
crossAxisSpacing: 12,
|
||||
childAspectRatio: 0.65,
|
||||
),
|
||||
itemCount: books.length,
|
||||
itemBuilder: (context, index) => _buildGridViewItem(books[index], colors),
|
||||
);
|
||||
}
|
||||
|
||||
return ListView.builder(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: books.length,
|
||||
itemBuilder: (context, index) => _buildListViewItem(books[index], colors),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildGridViewItem(ReaderBook book, ColorScheme colors) {
|
||||
return GestureDetector(
|
||||
onTap: () => _openBookDetail(book),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: colors.outlineVariant, width: 0.5),
|
||||
),
|
||||
child: Center(
|
||||
child: Icon(Icons.menu_book, size: 40, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(book.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
if (book.readingPercentage > 0)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 1),
|
||||
child: Text('${(book.readingPercentage * 100).toStringAsFixed(0)}%',
|
||||
style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildListViewItem(ReaderBook book, ColorScheme colors) {
|
||||
return GestureDetector(
|
||||
onTap: () => _openBookDetail(book),
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 64,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surface,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(Icons.menu_book, size: 24, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(book.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
const SizedBox(height: 4),
|
||||
Text('.${book.fileExtension}',
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (book.readingPercentage > 0)
|
||||
Text('${(book.readingPercentage * 100).toStringAsFixed(0)}%',
|
||||
style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
261
lib/pages/reader/epub_player.dart
Normal file
261
lib/pages/reader/epub_player.dart
Normal file
@@ -0,0 +1,261 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../service/book_server.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import '../../utils/reader_url_generator.dart';
|
||||
|
||||
/// 目录条目
|
||||
class TocItem {
|
||||
final String href;
|
||||
final String title;
|
||||
|
||||
TocItem({required this.href, required this.title});
|
||||
|
||||
factory TocItem.fromJson(Map<String, dynamic> json) {
|
||||
return TocItem(
|
||||
href: json['href'] ?? '',
|
||||
title: json['title'] ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 核心电子书阅读组件 — 使用 InAppWebView 渲染 foliate-js 阅读器
|
||||
class EpubPlayer extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
final String? initialCfi;
|
||||
final VoidCallback showOrHideToolbar;
|
||||
final ValueChanged<List<TocItem>>? onTocReady;
|
||||
|
||||
const EpubPlayer({
|
||||
super.key,
|
||||
required this.book,
|
||||
this.initialCfi,
|
||||
required this.showOrHideToolbar,
|
||||
this.onTocReady,
|
||||
});
|
||||
|
||||
@override
|
||||
State<EpubPlayer> createState() => EpubPlayerState();
|
||||
}
|
||||
|
||||
class EpubPlayerState extends State<EpubPlayer> {
|
||||
late InAppWebViewController _controller;
|
||||
String cfi = '';
|
||||
double percentage = 0.0;
|
||||
String chapterTitle = '';
|
||||
int chapterCurrentPage = 0;
|
||||
int chapterTotalPages = 0;
|
||||
|
||||
Timer? _styleTimer;
|
||||
|
||||
InAppWebViewSettings get _settings => InAppWebViewSettings(
|
||||
supportZoom: false,
|
||||
transparentBackground: true,
|
||||
useHybridComposition: true,
|
||||
mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW,
|
||||
);
|
||||
|
||||
// ─── 翻页方法 ───────────────────────────────────────
|
||||
|
||||
void prevPage() {
|
||||
_controller.evaluateJavascript(source: 'prevPage()');
|
||||
}
|
||||
|
||||
void nextPage() {
|
||||
_controller.evaluateJavascript(source: 'nextPage()');
|
||||
}
|
||||
|
||||
void prevChapter() {
|
||||
_controller.evaluateJavascript(source: 'prevSection()');
|
||||
}
|
||||
|
||||
void nextChapter() {
|
||||
_controller.evaluateJavascript(source: 'nextSection()');
|
||||
}
|
||||
|
||||
void goToPercentage(double value) {
|
||||
_controller.evaluateJavascript(source: 'goToPercent($value)');
|
||||
}
|
||||
|
||||
void goToHref(String href) {
|
||||
_controller.evaluateJavascript(source: "goToHref('$href')");
|
||||
}
|
||||
|
||||
void goToCfi(String cfi) {
|
||||
_controller.evaluateJavascript(source: "goToCfi('$cfi')");
|
||||
}
|
||||
|
||||
// ─── 样式方法 ───────────────────────────────────────
|
||||
|
||||
void changeStyle({
|
||||
double? fontSize,
|
||||
double? lineHeight,
|
||||
double? paragraphSpacing,
|
||||
String? fontColor,
|
||||
String? backgroundColor,
|
||||
}) {
|
||||
_styleTimer?.cancel();
|
||||
_styleTimer = Timer(const Duration(milliseconds: 200), () {
|
||||
if (!mounted) return;
|
||||
|
||||
final params = <String, dynamic>{};
|
||||
if (fontSize != null) params['fontSize'] = (fontSize * 100).round();
|
||||
if (lineHeight != null) params['spacing'] = lineHeight;
|
||||
if (paragraphSpacing != null) params['paragraphSpacing'] = paragraphSpacing;
|
||||
if (fontColor != null) params['fontColor'] = '#$fontColor';
|
||||
if (backgroundColor != null) params['backgroundColor'] = '#$backgroundColor';
|
||||
|
||||
if (params.isEmpty) return;
|
||||
|
||||
final jsonParams = jsonEncode(params);
|
||||
_controller.evaluateJavascript(source: 'changeStyle($jsonParams)');
|
||||
});
|
||||
}
|
||||
|
||||
void changeTheme(String bgColor, String textColor) {
|
||||
_controller.evaluateJavascript(source: '''
|
||||
changeStyle({
|
||||
backgroundColor: '#$bgColor',
|
||||
fontColor: '#$textColor',
|
||||
})
|
||||
''');
|
||||
}
|
||||
|
||||
// ─── 保存进度 ───────────────────────────────────────
|
||||
|
||||
Future<void> saveReadingProgress() async {
|
||||
if (cfi.isEmpty) return;
|
||||
final provider = context.read<AppProvider>();
|
||||
final updated = widget.book.copyWith(
|
||||
lastReadCfi: cfi,
|
||||
readingPercentage: percentage,
|
||||
updatedAt: DateTime.now(),
|
||||
);
|
||||
await provider.updateReaderBook(updated);
|
||||
}
|
||||
|
||||
// ─── WebView 回调 ───────────────────────────────────
|
||||
|
||||
Future<void> _onWebViewCreated(InAppWebViewController controller) async {
|
||||
_controller = controller;
|
||||
_setHandlers(controller);
|
||||
// 开启常亮
|
||||
WakelockPlus.enable();
|
||||
}
|
||||
|
||||
void _setHandlers(InAppWebViewController controller) {
|
||||
// 阅读位置变化
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onRelocated',
|
||||
callback: (args) {
|
||||
final location = args[0] as Map<String, dynamic>;
|
||||
setState(() {
|
||||
cfi = location['cfi'] ?? '';
|
||||
percentage = double.tryParse(location['percentage']?.toString() ?? '0') ?? 0.0;
|
||||
chapterTitle = location['chapterTitle'] ?? '';
|
||||
chapterCurrentPage = location['chapterCurrentPage'] ?? 0;
|
||||
chapterTotalPages = location['chapterTotalPages'] ?? 0;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// 点击事件(控制翻页和工具栏)
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onClick',
|
||||
callback: (args) {
|
||||
final location = args[0] as Map<String, dynamic>;
|
||||
final x = location['x'] as num?;
|
||||
final y = location['y'] as num?;
|
||||
if (x == null || y == null) return;
|
||||
|
||||
final pageWidth = MediaQuery.of(context).size.width;
|
||||
final clickX = x.toDouble() * pageWidth;
|
||||
final oneThird = pageWidth / 3;
|
||||
final twoThird = pageWidth * 2 / 3;
|
||||
|
||||
if (clickX < oneThird) {
|
||||
prevPage();
|
||||
} else if (clickX > twoThird) {
|
||||
nextPage();
|
||||
} else {
|
||||
widget.showOrHideToolbar();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// 目录数据
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onSetToc',
|
||||
callback: (args) {
|
||||
final List<dynamic> rawToc = args[0];
|
||||
final toc = rawToc.map((item) {
|
||||
if (item is Map) {
|
||||
return TocItem.fromJson(Map<String, dynamic>.from(item));
|
||||
}
|
||||
return TocItem(href: '', title: item.toString());
|
||||
}).toList();
|
||||
widget.onTocReady?.call(toc);
|
||||
},
|
||||
);
|
||||
|
||||
// 翻页上拉手势
|
||||
controller.addJavaScriptHandler(
|
||||
handlerName: 'onPullUp',
|
||||
callback: (args) {
|
||||
widget.showOrHideToolbar();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_styleTimer?.cancel();
|
||||
saveReadingProgress();
|
||||
WakelockPlus.disable();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDark = Theme.of(context).brightness == Brightness.dark;
|
||||
|
||||
final fileAbsolute = BookFileHelper.instance.resolveAbsolutePath(widget.book.filePath);
|
||||
final fileExists = fileAbsolute.isNotEmpty && File(fileAbsolute).existsSync();
|
||||
final bookUrl = 'http://127.0.0.1:${Server().port}/book/${Uri.encodeComponent(fileAbsolute)}';
|
||||
final initialCfi = widget.initialCfi ?? widget.book.lastReadCfi;
|
||||
|
||||
final bgColor = isDark ? 'FF1A1A1A' : 'FFFFFFFF';
|
||||
final textColor = isDark ? 'FFE5E5E5' : 'FF1A1A1A';
|
||||
|
||||
final url = generateReaderUrl(
|
||||
fileUrl: bookUrl,
|
||||
cfi: initialCfi,
|
||||
backgroundColor: bgColor,
|
||||
textColor: textColor,
|
||||
isDarkMode: isDark,
|
||||
);
|
||||
|
||||
debugPrint('[EpubPlayer] port=${Server().port} running=${Server().isRunning}');
|
||||
debugPrint('[EpubPlayer] fileAbsolute=$fileAbsolute exists=$fileExists');
|
||||
|
||||
return InAppWebView(
|
||||
initialUrlRequest: URLRequest(url: WebUri(url)),
|
||||
initialSettings: _settings,
|
||||
onWebViewCreated: _onWebViewCreated,
|
||||
onReceivedError: (controller, request, error) {
|
||||
debugPrint('[EpubPlayer] WebView error: ${error.description}');
|
||||
},
|
||||
onConsoleMessage: (controller, msg) {
|
||||
debugPrint('[EpubPlayer] JS: ${msg.message}');
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
114
lib/pages/reader/progress_panel.dart
Normal file
114
lib/pages/reader/progress_panel.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 进度控制面板 — 滑块跳转 + 章节信息
|
||||
class ProgressPanel extends StatefulWidget {
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
|
||||
const ProgressPanel({super.key, required this.epubPlayerKey});
|
||||
|
||||
@override
|
||||
State<ProgressPanel> createState() => _ProgressPanelState();
|
||||
}
|
||||
|
||||
class _ProgressPanelState extends State<ProgressPanel> {
|
||||
double _sliderValue = 0.0;
|
||||
Timer? _debounceTimer;
|
||||
|
||||
EpubPlayerState? get _player => widget.epubPlayerKey.currentState;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_sliderValue = _player?.percentage ?? 0.0;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_debounceTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final player = _player;
|
||||
final chapterTitle = player?.chapterTitle ?? '';
|
||||
final currentPage = player?.chapterCurrentPage ?? 0;
|
||||
final totalPages = player?.chapterTotalPages ?? 0;
|
||||
final percent = player?.percentage ?? 0.0;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 章节标题
|
||||
if (chapterTitle.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
chapterTitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: colors.onSurface),
|
||||
),
|
||||
),
|
||||
// 滑块行
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_previous, size: 20),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
|
||||
onPressed: () => _player?.prevChapter(),
|
||||
),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _sliderValue.clamp(0.0, 1.0),
|
||||
onChanged: (value) {
|
||||
setState(() => _sliderValue = value);
|
||||
_debounceTimer?.cancel();
|
||||
_debounceTimer = Timer(const Duration(milliseconds: 100), () {
|
||||
_player?.goToPercentage(value);
|
||||
});
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_next, size: 20),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(minWidth: 36, minHeight: 36),
|
||||
onPressed: () => _player?.nextChapter(),
|
||||
),
|
||||
],
|
||||
),
|
||||
// 页码和百分比
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 4),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_infoItem('$currentPage', '当前页', colors),
|
||||
_infoItem('$totalPages', '总页数', colors),
|
||||
_infoItem('${(percent * 100).toStringAsFixed(1)}%', '进度', colors),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _infoItem(String value, String label, ColorScheme colors) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(value, style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const SizedBox(height: 2),
|
||||
Text(label, style: TextStyle(fontSize: 10, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
187
lib/pages/reader/reader_book_detail_page.dart
Normal file
187
lib/pages/reader/reader_book_detail_page.dart
Normal file
@@ -0,0 +1,187 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../providers/app_provider.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import 'reading_page.dart';
|
||||
|
||||
/// 阅读器书籍详情页
|
||||
class ReaderBookDetailPage extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
|
||||
const ReaderBookDetailPage({super.key, required this.book});
|
||||
|
||||
@override
|
||||
State<ReaderBookDetailPage> createState() => _ReaderBookDetailPageState();
|
||||
}
|
||||
|
||||
class _ReaderBookDetailPageState extends State<ReaderBookDetailPage> {
|
||||
late String _title;
|
||||
late ReaderBook _book;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_book = widget.book;
|
||||
_title = _book.title;
|
||||
}
|
||||
|
||||
Future<void> _startReading() async {
|
||||
// 确保获取最新的book数据
|
||||
final provider = context.read<AppProvider>();
|
||||
final latest = provider.readerBooks.firstWhere(
|
||||
(b) => b.id == _book.id,
|
||||
orElse: () => _book,
|
||||
);
|
||||
if (context.mounted) {
|
||||
await Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ReadingPage(book: latest),
|
||||
),
|
||||
);
|
||||
// 返回后刷新
|
||||
if (mounted) {
|
||||
await provider.loadReaderBooks();
|
||||
final updated = provider.readerBooks.firstWhere(
|
||||
(b) => b.id == _book.id,
|
||||
orElse: () => _book,
|
||||
);
|
||||
setState(() {
|
||||
_book = updated;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteBook() async {
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: const Text('删除书籍'),
|
||||
content: Text('确定要删除「$_title」吗?\n此操作将同时删除书籍文件。'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: const Text('取消'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: const Text('删除', style: TextStyle(color: Colors.red)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed == true) {
|
||||
await BookFileHelper.instance.deleteBookFiles(_book.id);
|
||||
await context.read<AppProvider>().removeReaderBook(_book.id);
|
||||
if (mounted) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colors.surface,
|
||||
appBar: AppBar(
|
||||
title: const Text('书籍详情'),
|
||||
),
|
||||
body: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// 占位书封
|
||||
Center(
|
||||
child: Container(
|
||||
width: 140,
|
||||
height: 200,
|
||||
decoration: BoxDecoration(
|
||||
color: colors.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: colors.outlineVariant, width: 0.5),
|
||||
),
|
||||
child: Icon(Icons.menu_book, size: 64, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// 书名
|
||||
Text('书名', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text(_title, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 文件名
|
||||
Text('文件', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text('${_book.fileName} (.${_book.fileExtension})',
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 阅读进度
|
||||
Text('阅读进度', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: LinearProgressIndicator(
|
||||
value: _book.readingPercentage,
|
||||
minHeight: 8,
|
||||
backgroundColor: colors.surfaceContainerHighest,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Text('${(_book.readingPercentage * 100).toStringAsFixed(1)}%',
|
||||
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: colors.onSurface)),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// 导入时间
|
||||
Text('导入时间', style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.4))),
|
||||
const SizedBox(height: 4),
|
||||
Text(_book.createdAt.toString().substring(0, 10),
|
||||
style: TextStyle(fontSize: 14, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// 底部按钮
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton(
|
||||
onPressed: _deleteBook,
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
child: const Text('删除'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: FilledButton(
|
||||
onPressed: _startReading,
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(vertical: 14),
|
||||
),
|
||||
child: const Text('阅读'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
243
lib/pages/reader/reading_page.dart
Normal file
243
lib/pages/reader/reading_page.dart
Normal file
@@ -0,0 +1,243 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:pointer_interceptor/pointer_interceptor.dart';
|
||||
import '../../models/reader_book.dart';
|
||||
import '../../service/book_server.dart';
|
||||
import '../../utils/book_file_helper.dart';
|
||||
import 'epub_player.dart';
|
||||
import 'toc_drawer.dart';
|
||||
import 'progress_panel.dart';
|
||||
import 'style_panel.dart';
|
||||
|
||||
/// 书籍阅读页面
|
||||
class ReadingPage extends StatefulWidget {
|
||||
final ReaderBook book;
|
||||
|
||||
const ReadingPage({super.key, required this.book});
|
||||
|
||||
@override
|
||||
State<ReadingPage> createState() => _ReadingPageState();
|
||||
}
|
||||
|
||||
class _ReadingPageState extends State<ReadingPage> {
|
||||
final GlobalKey<EpubPlayerState> _epubPlayerKey = GlobalKey<EpubPlayerState>();
|
||||
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
|
||||
|
||||
static const _empty = SizedBox.shrink();
|
||||
bool _toolbarOffstage = true; // true=隐藏, false=显示
|
||||
Widget _currentPage = const SizedBox.shrink();
|
||||
bool _serverReady = false;
|
||||
|
||||
List<TocItem> _toc = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initServer();
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
|
||||
}
|
||||
|
||||
Future<void> _initServer() async {
|
||||
String _ = await BookFileHelper.instance.bookFileRoot;
|
||||
await Server().start(preferredPort: 0);
|
||||
if (mounted) setState(() => _serverReady = true);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_epubPlayerKey.currentState?.saveReadingProgress();
|
||||
Server().stop();
|
||||
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _showToolbar() {
|
||||
setState(() {
|
||||
_toolbarOffstage = false;
|
||||
});
|
||||
}
|
||||
|
||||
void _hideToolbar() {
|
||||
setState(() {
|
||||
_currentPage = _empty;
|
||||
_toolbarOffstage = true;
|
||||
});
|
||||
}
|
||||
|
||||
void _toggleToolbar() {
|
||||
if (_toolbarOffstage) {
|
||||
_showToolbar();
|
||||
} else {
|
||||
_hideToolbar();
|
||||
}
|
||||
}
|
||||
|
||||
void _onTocReady(List<TocItem> toc) {
|
||||
if (mounted) setState(() => _toc = toc);
|
||||
}
|
||||
|
||||
void _openTocDrawer() {
|
||||
_hideToolbar();
|
||||
_scaffoldKey.currentState?.openDrawer();
|
||||
}
|
||||
|
||||
// ─── 底部面板切换 ─────────────────────────────────────
|
||||
|
||||
void _onProgressPressed() {
|
||||
setState(() {
|
||||
_currentPage = ProgressPanel(epubPlayerKey: _epubPlayerKey);
|
||||
});
|
||||
}
|
||||
|
||||
void _onStylePressed() {
|
||||
setState(() {
|
||||
_currentPage = StylePanel(epubPlayerKey: _epubPlayerKey);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
// ─── 工具栏覆盖层(照抄 anx-reader 的 Offstage + PointerInterceptor 模式)
|
||||
Offstage controller = Offstage(
|
||||
offstage: _toolbarOffstage,
|
||||
child: PointerInterceptor(
|
||||
child: Stack(
|
||||
children: [
|
||||
// 半透明背景,点击关闭工具栏
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
onTap: _hideToolbar,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onVerticalDragUpdate: (details) {},
|
||||
onVerticalDragEnd: (details) {},
|
||||
child: Container(
|
||||
color: Colors.black.withValues(alpha: 0.15),
|
||||
),
|
||||
),
|
||||
),
|
||||
// 顶部 AppBar + 底部工具栏
|
||||
Column(
|
||||
children: [
|
||||
// 顶部 AppBar
|
||||
AppBar(
|
||||
backgroundColor: colors.surface.withValues(alpha: 0.94),
|
||||
title: Text(widget.book.title, overflow: TextOverflow.ellipsis),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
// 底部面板 + 按钮行
|
||||
BottomSheet(
|
||||
onClosing: () {},
|
||||
enableDrag: false,
|
||||
builder: (context) => SafeArea(
|
||||
top: false,
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(maxWidth: 600),
|
||||
child: StatefulBuilder(
|
||||
builder: (BuildContext context, StateSetter modalSetState) {
|
||||
final hasContent = !identical(_currentPage, _empty);
|
||||
return IntrinsicHeight(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 面板内容区域
|
||||
if (hasContent)
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
child: _currentPage,
|
||||
),
|
||||
),
|
||||
// 按钮行
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.toc),
|
||||
tooltip: '目录',
|
||||
onPressed: _openTocDrawer,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.data_usage),
|
||||
tooltip: '进度',
|
||||
onPressed: () {
|
||||
modalSetState(() {
|
||||
_onProgressPressed();
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.color_lens),
|
||||
tooltip: '样式',
|
||||
onPressed: () {
|
||||
modalSetState(() {
|
||||
_onStylePressed();
|
||||
});
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_previous),
|
||||
tooltip: '上一章',
|
||||
onPressed: () {
|
||||
_epubPlayerKey.currentState?.prevChapter();
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.skip_next),
|
||||
tooltip: '下一章',
|
||||
onPressed: () {
|
||||
_epubPlayerKey.currentState?.nextChapter();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
key: _scaffoldKey,
|
||||
backgroundColor: colors.surface,
|
||||
// TOC 目录抽屉
|
||||
drawer: PointerInterceptor(
|
||||
child: Drawer(
|
||||
width: MediaQuery.of(context).size.width * 0.75,
|
||||
child: TocDrawer(
|
||||
toc: _toc,
|
||||
epubPlayerKey: _epubPlayerKey,
|
||||
),
|
||||
),
|
||||
),
|
||||
body: _serverReady
|
||||
? Stack(
|
||||
children: [
|
||||
// 阅读内容(WebView)
|
||||
EpubPlayer(
|
||||
key: _epubPlayerKey,
|
||||
book: widget.book,
|
||||
showOrHideToolbar: _toggleToolbar,
|
||||
onTocReady: _onTocReady,
|
||||
),
|
||||
// 工具栏覆盖层
|
||||
controller,
|
||||
],
|
||||
)
|
||||
: const Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
}
|
||||
162
lib/pages/reader/style_panel.dart
Normal file
162
lib/pages/reader/style_panel.dart
Normal file
@@ -0,0 +1,162 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../utils/user_prefs.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 预设主题
|
||||
const _presetThemes = [
|
||||
{'bg': 'FFFFFFFF', 'fg': 'FF1A1A1A', 'name': '默认'},
|
||||
{'bg': 'FF1A1A1A', 'fg': 'FFE5E5E5', 'name': '暗黑'},
|
||||
{'bg': 'FFF8F0E3', 'fg': 'FF333333', 'name': '护眼'},
|
||||
{'bg': 'FF2B2B2B', 'fg': 'FFCCCCCC', 'name': '深灰'},
|
||||
{'bg': 'FF2D3E50', 'fg': 'FFD4D4D4', 'name': '蓝灰'},
|
||||
];
|
||||
|
||||
/// 样式设置面板 — 字号、行距、主题
|
||||
class StylePanel extends StatefulWidget {
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
|
||||
const StylePanel({super.key, required this.epubPlayerKey});
|
||||
|
||||
@override
|
||||
State<StylePanel> createState() => _StylePanelState();
|
||||
}
|
||||
|
||||
class _StylePanelState extends State<StylePanel> {
|
||||
double _fontSize = 1.0;
|
||||
double _lineHeight = 1.6;
|
||||
int _selectedTheme = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadPrefs();
|
||||
}
|
||||
|
||||
void _loadPrefs() {
|
||||
final sp = UserPrefs().prefs;
|
||||
setState(() {
|
||||
_fontSize = sp.getDouble('reader_font_size') ?? 1.0;
|
||||
_lineHeight = sp.getDouble('reader_line_height') ?? 1.6;
|
||||
_selectedTheme = sp.getInt('reader_theme_index') ?? 0;
|
||||
});
|
||||
}
|
||||
|
||||
void _savePrefs() {
|
||||
final sp = UserPrefs().prefs;
|
||||
sp.setDouble('reader_font_size', _fontSize);
|
||||
sp.setDouble('reader_line_height', _lineHeight);
|
||||
sp.setInt('reader_theme_index', _selectedTheme);
|
||||
}
|
||||
|
||||
void _applyStyle() {
|
||||
widget.epubPlayerKey.currentState?.changeStyle(
|
||||
fontSize: _fontSize,
|
||||
lineHeight: _lineHeight,
|
||||
);
|
||||
_savePrefs();
|
||||
}
|
||||
|
||||
void _applyTheme(int index) {
|
||||
final theme = _presetThemes[index];
|
||||
final bg = theme['bg']!;
|
||||
final fg = theme['fg']!;
|
||||
widget.epubPlayerKey.currentState?.changeTheme(bg, fg);
|
||||
setState(() => _selectedTheme = index);
|
||||
_savePrefs();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// 字号
|
||||
Row(
|
||||
children: [
|
||||
Text('字号', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _fontSize,
|
||||
min: 0.5,
|
||||
max: 3.0,
|
||||
divisions: 25,
|
||||
label: '${(_fontSize * 100).round()}%',
|
||||
onChanged: (value) {
|
||||
setState(() => _fontSize = value);
|
||||
_applyStyle();
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 44,
|
||||
child: Text('${(_fontSize * 100).round()}%',
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))),
|
||||
),
|
||||
],
|
||||
),
|
||||
// 行距
|
||||
Row(
|
||||
children: [
|
||||
Text('行距', style: TextStyle(fontSize: 13, color: colors.onSurface.withValues(alpha: 0.6))),
|
||||
Expanded(
|
||||
child: Slider(
|
||||
value: _lineHeight,
|
||||
min: 1.0,
|
||||
max: 3.0,
|
||||
divisions: 20,
|
||||
label: _lineHeight.toStringAsFixed(1),
|
||||
onChanged: (value) {
|
||||
setState(() => _lineHeight = value);
|
||||
_applyStyle();
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
width: 44,
|
||||
child: Text(_lineHeight.toStringAsFixed(1),
|
||||
textAlign: TextAlign.end,
|
||||
style: TextStyle(fontSize: 12, color: colors.onSurface.withValues(alpha: 0.5))),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// 主题色块
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: List.generate(_presetThemes.length, (index) {
|
||||
final theme = _presetThemes[index];
|
||||
final bg = Color(int.parse(theme['bg']!, radix: 16));
|
||||
final fg = Color(int.parse(theme['fg']!, radix: 16));
|
||||
final isSelected = index == _selectedTheme;
|
||||
|
||||
return GestureDetector(
|
||||
onTap: () => _applyTheme(index),
|
||||
child: Container(
|
||||
width: 42,
|
||||
height: 42,
|
||||
margin: const EdgeInsets.symmetric(horizontal: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: bg,
|
||||
borderRadius: BorderRadius.circular(21),
|
||||
border: Border.all(
|
||||
color: isSelected ? colors.primary : colors.outlineVariant,
|
||||
width: isSelected ? 2.5 : 1,
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text('A', style: TextStyle(color: fg, fontSize: 16, fontWeight: FontWeight.w500)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
77
lib/pages/reader/toc_drawer.dart
Normal file
77
lib/pages/reader/toc_drawer.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'epub_player.dart';
|
||||
|
||||
/// 目录抽屉 — 显示书籍章节目录,点击跳转
|
||||
class TocDrawer extends StatelessWidget {
|
||||
final List<TocItem> toc;
|
||||
final GlobalKey<EpubPlayerState> epubPlayerKey;
|
||||
final VoidCallback? onClose;
|
||||
|
||||
const TocDrawer({
|
||||
super.key,
|
||||
required this.toc,
|
||||
required this.epubPlayerKey,
|
||||
this.onClose,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
|
||||
return Container(
|
||||
color: colors.surface,
|
||||
child: SafeArea(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.toc, size: 20, color: colors.onSurface.withValues(alpha: 0.6)),
|
||||
const SizedBox(width: 10),
|
||||
Text('目录', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: colors.onSurface)),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: onClose ?? () => Navigator.pop(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(height: 1, color: colors.outlineVariant),
|
||||
Expanded(
|
||||
child: toc.isEmpty
|
||||
? Center(
|
||||
child: Text('暂无目录', style: TextStyle(color: colors.onSurface.withValues(alpha: 0.3))),
|
||||
)
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
itemCount: toc.length,
|
||||
itemBuilder: (context, index) {
|
||||
final item = toc[index];
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
epubPlayerKey.currentState?.goToHref(item.href);
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
|
||||
child: Text(
|
||||
item.title,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: colors.onSurface.withValues(alpha: 0.8),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import '../utils/movie/movie_poster_dao.dart';
|
||||
import '../utils/book/book_review_dao.dart';
|
||||
import '../utils/book/book_excerpt_dao.dart';
|
||||
import '../utils/tag/tag_dao.dart';
|
||||
import '../utils/reader_book_dao.dart';
|
||||
import '../models/reader_book.dart';
|
||||
import '../utils/database_helper.dart';
|
||||
import '../utils/image_path_helper.dart';
|
||||
import '../utils/user_prefs.dart';
|
||||
@@ -25,11 +27,13 @@ class AppProvider extends ChangeNotifier {
|
||||
final BookReviewDao _bookReviewDao = BookReviewDao();
|
||||
final BookExcerptDao _bookExcerptDao = BookExcerptDao();
|
||||
final TagDao _tagDao = TagDao();
|
||||
final ReaderBookDao _readerBookDao = ReaderBookDao();
|
||||
|
||||
// 数据列表
|
||||
List<Movie> _movies = [];
|
||||
List<Book> _books = [];
|
||||
List<Note> _notes = [];
|
||||
List<ReaderBook> _readerBooks = [];
|
||||
|
||||
// 当前主界面选中的标签 (0: 观影,1: 阅读,2: 笔记)
|
||||
int _mainTabIndex = 0;
|
||||
@@ -60,6 +64,10 @@ class AppProvider extends ChangeNotifier {
|
||||
|
||||
// 侧边菜单是否打开
|
||||
bool _drawerOpen = false;
|
||||
|
||||
// 回到顶部信号(点击首页图标时递增)
|
||||
int _scrollToTopSignal = 0;
|
||||
int get scrollToTopSignal => _scrollToTopSignal;
|
||||
|
||||
// 初始化数据库
|
||||
Future<void> initDatabase() async {
|
||||
@@ -73,10 +81,12 @@ class AppProvider extends ChangeNotifier {
|
||||
_movieDao.getAllMovies(),
|
||||
_bookDao.getAllBooks(),
|
||||
_noteDao.getAllNotes(),
|
||||
_readerBookDao.getAllReaderBooks(),
|
||||
]);
|
||||
_movies = results[0] as List<Movie>;
|
||||
_books = results[1] as List<Book>;
|
||||
_notes = results[2] as List<Note>;
|
||||
_readerBooks = results[3] as List<ReaderBook>;
|
||||
debugPrint('[AppProvider] 本地数据: movies=${_movies.length}, books=${_books.length}, notes=${_notes.length}');
|
||||
notifyListeners();
|
||||
}
|
||||
@@ -144,6 +154,26 @@ class AppProvider extends ChangeNotifier {
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> loadReaderBooks() async {
|
||||
_readerBooks = await _readerBookDao.getAllReaderBooks();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<void> addReaderBook(ReaderBook book) async {
|
||||
await _readerBookDao.insertReaderBook(book);
|
||||
await loadReaderBooks();
|
||||
}
|
||||
|
||||
Future<void> updateReaderBook(ReaderBook book) async {
|
||||
await _readerBookDao.updateReaderBook(book);
|
||||
await loadReaderBooks();
|
||||
}
|
||||
|
||||
Future<void> removeReaderBook(String id) async {
|
||||
await _readerBookDao.deleteReaderBook(id);
|
||||
await loadReaderBooks();
|
||||
}
|
||||
|
||||
// ─── 分页加载(供列表页触底加载使用)────────────────────────
|
||||
static const int _pageSize = 20;
|
||||
|
||||
@@ -179,6 +209,7 @@ class AppProvider extends ChangeNotifier {
|
||||
List<Movie> get movies => _movies;
|
||||
List<Book> get books => _books;
|
||||
List<Note> get notes => _notes;
|
||||
List<ReaderBook> get readerBooks => _readerBooks;
|
||||
|
||||
// 根据状态获取影视列表
|
||||
List<Movie> getMoviesByStatus(String status) {
|
||||
@@ -197,8 +228,14 @@ class AppProvider extends ChangeNotifier {
|
||||
}
|
||||
|
||||
void setBottomNavIndex(int index) {
|
||||
if (index == 0 && _bottomNavIndex == 0) {
|
||||
// 已在首页,再次点击 → 回到顶部
|
||||
_scrollToTopSignal++;
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
_bottomNavIndex = index;
|
||||
_bottomNavVisible = true; // 切换页面时自动显示导航栏
|
||||
_bottomNavVisible = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
|
||||
75
lib/service/book_import_service.dart
Normal file
75
lib/service/book_import_service.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
import 'dart:io';
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:uuid/uuid.dart';
|
||||
import '../models/reader_book.dart';
|
||||
import '../providers/app_provider.dart';
|
||||
import '../utils/book_file_helper.dart';
|
||||
|
||||
/// 书籍导入服务
|
||||
class BookImportService {
|
||||
static const allowedExtensions = ['epub', 'txt'];
|
||||
|
||||
static Future<ReaderBook?> pickAndImportBook(
|
||||
BuildContext context,
|
||||
AppProvider provider,
|
||||
) async {
|
||||
final result = await FilePicker.platform.pickFiles(
|
||||
type: FileType.custom,
|
||||
allowedExtensions: allowedExtensions,
|
||||
allowMultiple: false,
|
||||
);
|
||||
|
||||
if (result == null || result.files.isEmpty) return null;
|
||||
|
||||
final platformFile = result.files.first;
|
||||
final sourcePath = platformFile.path;
|
||||
if (sourcePath == null) return null;
|
||||
|
||||
final file = File(sourcePath);
|
||||
if (!await file.exists()) return null;
|
||||
|
||||
final extension = p.extension(file.path).replaceAll('.', '').toLowerCase();
|
||||
if (!allowedExtensions.contains(extension)) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('不支持的格式:$extension')),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
final title = p.basenameWithoutExtension(platformFile.name);
|
||||
final helper = BookFileHelper.instance;
|
||||
final id = const Uuid().v4();
|
||||
|
||||
// 清理文件名,去除特殊字符
|
||||
final safeName = platformFile.name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
|
||||
final destPath = await helper.bookFile(id, safeName);
|
||||
|
||||
// 复制文件
|
||||
await file.copy(destPath);
|
||||
|
||||
final now = DateTime.now();
|
||||
final readerBook = ReaderBook(
|
||||
id: id,
|
||||
title: title,
|
||||
fileName: platformFile.name,
|
||||
filePath: '$id/$safeName', // 相对路径
|
||||
fileExtension: extension,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
);
|
||||
|
||||
await provider.addReaderBook(readerBook);
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('「$title」导入成功')),
|
||||
);
|
||||
}
|
||||
|
||||
return readerBook;
|
||||
}
|
||||
}
|
||||
98
lib/service/book_server.dart
Normal file
98
lib/service/book_server.dart
Normal file
@@ -0,0 +1,98 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:shelf/shelf.dart' as shelf;
|
||||
import 'package:shelf/shelf_io.dart' as io;
|
||||
|
||||
/// 本地 HTTP 服务器,为 WebView 提供书籍文件和 foliate-js 资源
|
||||
class Server {
|
||||
static final Server _singleton = Server._internal();
|
||||
factory Server() => _singleton;
|
||||
Server._internal();
|
||||
|
||||
HttpServer? _server;
|
||||
bool get isRunning => _server != null;
|
||||
int get port => _server?.port ?? 0;
|
||||
|
||||
Future<void> start({int preferredPort = 0}) async {
|
||||
if (_server != null) {
|
||||
await stop();
|
||||
}
|
||||
|
||||
final handler = const shelf.Pipeline()
|
||||
.addMiddleware(shelf.logRequests())
|
||||
.addHandler(_handleRequest);
|
||||
|
||||
try {
|
||||
_server = await io.serve(handler, '127.0.0.1', preferredPort);
|
||||
} catch (_) {
|
||||
_server = await io.serve(handler, '127.0.0.1', 0);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (_server == null) return;
|
||||
await _server!.close(force: true);
|
||||
_server = null;
|
||||
}
|
||||
|
||||
Future<shelf.Response> _handleRequest(shelf.Request request) async {
|
||||
final uriPath = request.requestedUri.path;
|
||||
|
||||
// 书籍文件请求
|
||||
if (uriPath.startsWith('/book/')) {
|
||||
final bookPath = Uri.decodeComponent(uriPath.substring(6));
|
||||
final file = File(bookPath);
|
||||
if (!await file.exists()) {
|
||||
return shelf.Response.notFound('Book not found');
|
||||
}
|
||||
return shelf.Response.ok(
|
||||
file.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/epub+zip',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// foliate-js 资源请求
|
||||
if (uriPath.startsWith('/foliate-js/')) {
|
||||
final assetPath = 'assets/foliate-js/${uriPath.substring(12)}';
|
||||
|
||||
String contentType;
|
||||
if (uriPath.endsWith('.html')) {
|
||||
contentType = 'text/html';
|
||||
} else if (uriPath.endsWith('.css')) {
|
||||
contentType = 'text/css';
|
||||
} else if (uriPath.endsWith('.js') || uriPath.endsWith('.mjs')) {
|
||||
contentType = 'application/javascript';
|
||||
} else if (uriPath.endsWith('.json')) {
|
||||
contentType = 'application/json';
|
||||
} else if (uriPath.endsWith('.svg')) {
|
||||
contentType = 'image/svg+xml';
|
||||
} else {
|
||||
contentType = 'application/octet-stream';
|
||||
}
|
||||
|
||||
try {
|
||||
// 优先尝试 load() 加载为字节流(最可靠),再转为字符串或直接返回
|
||||
final data = await rootBundle.load(assetPath);
|
||||
return shelf.Response.ok(
|
||||
data.buffer.asUint8List(),
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[Server] Asset not found: $assetPath error=$e');
|
||||
return shelf.Response.notFound('Asset not found: $assetPath');
|
||||
}
|
||||
}
|
||||
|
||||
return shelf.Response.ok(
|
||||
'OK',
|
||||
headers: {'Access-Control-Allow-Origin': '*'},
|
||||
);
|
||||
}
|
||||
}
|
||||
71
lib/utils/book_file_helper.dart
Normal file
71
lib/utils/book_file_helper.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
import 'dart:io';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// 阅读器文件路径管理
|
||||
class BookFileHelper {
|
||||
static final BookFileHelper instance = BookFileHelper._init();
|
||||
BookFileHelper._init();
|
||||
|
||||
String? _rootPath;
|
||||
|
||||
Future<String> get _root async {
|
||||
if (_rootPath != null) return _rootPath!;
|
||||
final dir = await getApplicationDocumentsDirectory();
|
||||
_rootPath = p.join(dir.path, 'mooknote', 'book_file');
|
||||
await Directory(_rootPath!).create(recursive: true);
|
||||
return _rootPath!;
|
||||
}
|
||||
|
||||
Future<String> get bookFileRoot async => _root;
|
||||
|
||||
Future<String> get coverDir async {
|
||||
final root = await _root;
|
||||
final dir = p.join(root, 'cover');
|
||||
await Directory(dir).create(recursive: true);
|
||||
return dir;
|
||||
}
|
||||
|
||||
Future<String> bookDir(String bookId) async {
|
||||
final root = await _root;
|
||||
final dir = p.join(root, bookId);
|
||||
await Directory(dir).create(recursive: true);
|
||||
return dir;
|
||||
}
|
||||
|
||||
Future<String> bookFile(String bookId, String fileName) async {
|
||||
final dir = await bookDir(bookId);
|
||||
return p.join(dir, fileName);
|
||||
}
|
||||
|
||||
String? relativePath(String absolutePath) {
|
||||
if (_rootPath == null) return null;
|
||||
if (absolutePath.startsWith(_rootPath!)) {
|
||||
return absolutePath.substring(_rootPath!.length + 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<String> absolutePath(String relativePath) async {
|
||||
final root = await _root;
|
||||
return p.join(root, relativePath);
|
||||
}
|
||||
|
||||
Future<void> deleteBookFiles(String bookId) async {
|
||||
final dir = await bookDir(bookId);
|
||||
if (await Directory(dir).exists()) {
|
||||
await Directory(dir).delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步初始化(必须在使用 resolveAbsolutePath 前调用一次 bookFileRoot)
|
||||
Future<void> ensureInitialized() async {
|
||||
await _root;
|
||||
}
|
||||
|
||||
/// 根据相对路径解析绝对路径(调用前需确保已初始化)
|
||||
String resolveAbsolutePath(String relativePath) {
|
||||
if (_rootPath == null) return relativePath;
|
||||
return p.join(_rootPath!, relativePath);
|
||||
}
|
||||
}
|
||||
6
lib/utils/color_converter.dart
Normal file
6
lib/utils/color_converter.dart
Normal file
@@ -0,0 +1,6 @@
|
||||
/// Dart ARGB 颜色字符串转换为 JS RGBA 格式
|
||||
/// dartColor: "FF0066FF" (AARRGGBB) → jsColor: "0066FFFF" (RRGGBBAA)
|
||||
String convertDartColorToJs(String dartColor) {
|
||||
if (dartColor.length < 8) return dartColor;
|
||||
return dartColor.substring(2) + dartColor.substring(0, 2);
|
||||
}
|
||||
@@ -57,7 +57,7 @@ class DatabaseHelper {
|
||||
|
||||
return await openDatabase(
|
||||
path,
|
||||
version: 13,
|
||||
version: 14,
|
||||
onCreate: _createDB,
|
||||
onUpgrade: _onUpgrade,
|
||||
);
|
||||
@@ -115,6 +115,9 @@ class DatabaseHelper {
|
||||
if (oldVersion < 13) {
|
||||
await _upgradeToV13(db);
|
||||
}
|
||||
if (oldVersion < 14) {
|
||||
await _createReaderBooksTable(db);
|
||||
}
|
||||
}
|
||||
|
||||
/// 升级books表到V11(添加ISBN和出版时间字段)
|
||||
@@ -154,6 +157,26 @@ class DatabaseHelper {
|
||||
}
|
||||
}
|
||||
|
||||
/// 升级到V14:创建阅读器书籍表
|
||||
Future<void> _createReaderBooksTable(Database db) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE IF NOT EXISTS reader_books (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
author TEXT DEFAULT '',
|
||||
cover_path TEXT,
|
||||
file_path TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
file_extension TEXT NOT NULL DEFAULT 'epub',
|
||||
last_read_cfi TEXT DEFAULT '',
|
||||
reading_percentage REAL DEFAULT 0.0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
is_deleted INTEGER DEFAULT 0
|
||||
)
|
||||
''');
|
||||
}
|
||||
|
||||
/// 升级到V13:创建标签表并回填已有数据
|
||||
Future<void> _upgradeToV13(Database db) async {
|
||||
await db.execute('''
|
||||
@@ -587,6 +610,24 @@ class DatabaseHelper {
|
||||
UNIQUE(name, type)
|
||||
)
|
||||
''');
|
||||
|
||||
// 阅读器书籍表
|
||||
await db.execute('''
|
||||
CREATE TABLE IF NOT EXISTS reader_books (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
author TEXT DEFAULT '',
|
||||
cover_path TEXT,
|
||||
file_path TEXT NOT NULL,
|
||||
file_name TEXT NOT NULL,
|
||||
file_extension TEXT NOT NULL DEFAULT 'epub',
|
||||
last_read_cfi TEXT DEFAULT '',
|
||||
reading_percentage REAL DEFAULT 0.0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
is_deleted INTEGER DEFAULT 0
|
||||
)
|
||||
''');
|
||||
}
|
||||
|
||||
// 关闭数据库
|
||||
|
||||
69
lib/utils/reader_book_dao.dart
Normal file
69
lib/utils/reader_book_dao.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/reader_book.dart';
|
||||
import 'database_helper.dart';
|
||||
|
||||
/// 阅读器书籍 DAO
|
||||
class ReaderBookDao {
|
||||
final DatabaseHelper _dbHelper = DatabaseHelper.instance;
|
||||
|
||||
Future<T> _wrap<T>(String op, Future<T> Function() fn) async {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (e) {
|
||||
debugPrint('[ReaderBookDao] $op error: $e');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<ReaderBook>> getAllReaderBooks() => _wrap('getAllReaderBooks', () async {
|
||||
final db = await _dbHelper.database;
|
||||
final List<Map<String, dynamic>> maps = await db.query(
|
||||
'reader_books',
|
||||
where: 'is_deleted = ?',
|
||||
whereArgs: [0],
|
||||
orderBy: 'created_at DESC',
|
||||
);
|
||||
return List.generate(maps.length, (i) => ReaderBook.fromJson(maps[i]));
|
||||
});
|
||||
|
||||
Future<ReaderBook?> getReaderBookById(String id) => _wrap('getReaderBookById', () async {
|
||||
final db = await _dbHelper.database;
|
||||
final List<Map<String, dynamic>> maps = await db.query(
|
||||
'reader_books',
|
||||
where: 'id = ? AND is_deleted = ?',
|
||||
whereArgs: [id, 0],
|
||||
);
|
||||
if (maps.isEmpty) return null;
|
||||
return ReaderBook.fromJson(maps.first);
|
||||
});
|
||||
|
||||
Future<void> insertReaderBook(ReaderBook book) => _wrap('insertReaderBook', () async {
|
||||
final db = await _dbHelper.database;
|
||||
await db.insert('reader_books', book.toJson());
|
||||
});
|
||||
|
||||
Future<void> updateReaderBook(ReaderBook book) => _wrap('updateReaderBook', () async {
|
||||
final db = await _dbHelper.database;
|
||||
await db.update(
|
||||
'reader_books',
|
||||
book.toJson(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [book.id],
|
||||
);
|
||||
});
|
||||
|
||||
Future<void> deleteReaderBook(String id) => _wrap('deleteReaderBook', () async {
|
||||
final db = await _dbHelper.database;
|
||||
await db.update(
|
||||
'reader_books',
|
||||
{'is_deleted': 1, 'updated_at': DateTime.now().toIso8601String()},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
});
|
||||
|
||||
Future<void> permanentDeleteReaderBook(String id) => _wrap('permanentDeleteReaderBook', () async {
|
||||
final db = await _dbHelper.database;
|
||||
await db.delete('reader_books', where: 'id = ?', whereArgs: [id]);
|
||||
});
|
||||
}
|
||||
69
lib/utils/reader_url_generator.dart
Normal file
69
lib/utils/reader_url_generator.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'dart:convert';
|
||||
import '../service/book_server.dart';
|
||||
import 'color_converter.dart';
|
||||
|
||||
/// 生成 foliate-js 阅读器 URL
|
||||
String generateReaderUrl({
|
||||
required String fileUrl,
|
||||
String cfi = '',
|
||||
required String backgroundColor,
|
||||
required String textColor,
|
||||
bool isDarkMode = false,
|
||||
}) {
|
||||
final indexHtmlPath = 'http://127.0.0.1:${Server().port}/foliate-js/index.html';
|
||||
|
||||
final jsBg = convertDartColorToJs(backgroundColor);
|
||||
final jsTc = convertDartColorToJs(textColor);
|
||||
|
||||
final style = {
|
||||
'fontSize': 100, // 100 = base 100%
|
||||
'fontName': '',
|
||||
'fontPath': '',
|
||||
'fontWeight': 400,
|
||||
'letterSpacing': 0,
|
||||
'spacing': 1.6,
|
||||
'paragraphSpacing': 0.6,
|
||||
'textIndent': 2,
|
||||
'fontColor': '#$jsTc',
|
||||
'backgroundColor': '#$jsBg',
|
||||
'topMargin': 25,
|
||||
'bottomMargin': 25,
|
||||
'sideMargin': 15,
|
||||
'justify': true,
|
||||
'hyphenate': false,
|
||||
'pageTurnStyle': 'slide',
|
||||
'maxColumnCount': 1,
|
||||
'columnThreshold': 3,
|
||||
'writingMode': 'horizontal-tb',
|
||||
'textAlign': 'justify',
|
||||
'backgroundImage': '',
|
||||
'bgimgBlur': 0,
|
||||
'bgimgOpacity': 1.0,
|
||||
'bgimgFit': 'cover',
|
||||
'allowScript': false,
|
||||
'customCSS': '',
|
||||
'customCSSEnabled': false,
|
||||
'useBookStyles': true,
|
||||
'headingFontSize': 130,
|
||||
'codeHighlightTheme': 'atom-one-light',
|
||||
};
|
||||
|
||||
final readingRules = {
|
||||
'convertChineseMode': 'none',
|
||||
'bionicReadingMode': false,
|
||||
};
|
||||
|
||||
final params = {
|
||||
'importing': false,
|
||||
'url': fileUrl,
|
||||
'initialCfi': cfi,
|
||||
'style': style,
|
||||
'readingRules': readingRules,
|
||||
};
|
||||
|
||||
final queryParts = params.entries
|
||||
.map((e) => '${e.key}=${Uri.encodeComponent(jsonEncode(e.value))}')
|
||||
.join('&');
|
||||
|
||||
return '$indexHtmlPath?$queryParts';
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import '../utils/user_prefs.dart';
|
||||
import '../pages/stroll_page.dart';
|
||||
import '../pages/markdown_reader/md_reader_tab_page.dart';
|
||||
import '../pages/tag_management_page.dart';
|
||||
import '../pages/reader/bookshelf_page.dart';
|
||||
import '../pages/profile_page.dart';
|
||||
import '../pages/movies/movie_detail_page.dart';
|
||||
import '../pages/book/book_detail_page.dart';
|
||||
@@ -180,16 +181,24 @@ class _CustomDrawerState extends State<CustomDrawer> {
|
||||
_buildToolItem(Icons.description_outlined, 'MD阅读', () {
|
||||
Navigator.pop(context);
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => const MdReaderTabPage()));
|
||||
}, bottomRounded: true),
|
||||
}),
|
||||
Divider(height: 1, indent: 52, endIndent: 20, color: colors.outlineVariant),
|
||||
_buildToolItem(Icons.menu_book_outlined, '阅读器', () {
|
||||
Navigator.pop(context);
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => const BookshelfPage()));
|
||||
}, bottomRounded: true, enabled: false),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildToolItem(IconData icon, String title, VoidCallback onTap, {bool topRounded = false, bool bottomRounded = false}) {
|
||||
Widget _buildToolItem(IconData icon, String title, VoidCallback onTap, {bool topRounded = false, bool bottomRounded = false, bool enabled = true}) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final effectiveOnTap = enabled ? onTap : null;
|
||||
final iconOpacity = enabled ? 0.7 : 0.25;
|
||||
final textOpacity = enabled ? 1.0 : 0.35;
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
onTap: effectiveOnTap,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: topRounded ? const Radius.circular(16) : Radius.zero,
|
||||
topRight: topRounded ? const Radius.circular(16) : Radius.zero,
|
||||
@@ -200,9 +209,9 @@ class _CustomDrawerState extends State<CustomDrawer> {
|
||||
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 20),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 20, color: colors.onSurface.withValues(alpha: 0.7)),
|
||||
Icon(icon, size: 20, color: colors.onSurface.withValues(alpha: iconOpacity)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(title, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: colors.onSurface))),
|
||||
Expanded(child: Text(title, style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500, color: colors.onSurface.withValues(alpha: textOpacity)))),
|
||||
Icon(Icons.chevron_right, size: 16, color: colors.onSurface.withValues(alpha: 0.2)),
|
||||
],
|
||||
),
|
||||
|
||||
Reference in New Issue
Block a user