Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat(search): redesign image search

Predidita71dfa213b0e
diff --git a/lib/pages/search/image_search_page.dart b/lib/pages/search/image_search_page.dart
index 7a3b898c..e8a9c1bc 100644
--- a/lib/pages/search/image_search_page.dart
+++ b/lib/pages/search/image_search_page.dart
@@ -2,25 +2,24 @@ import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:image_picker/image_picker.dart';
+import 'package:material_new_shapes/material_new_shapes.dart';
+import 'package:path/path.dart' as path;
import 'package:url_launcher/url_launcher.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
-import 'package:kazumi/bean/card/network_img_layer.dart';
-import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/modules/search/image_search_module.dart';
import 'package:kazumi/pages/search/search_controller.dart';
-import 'package:kazumi/utils/constants.dart';
-import 'package:kazumi/utils/format.dart';
+
+part 'image_search_widgets.dart';
class ImageSearchPage extends StatefulWidget {
- const ImageSearchPage({
- super.key,
- required this.controller,
- });
+ const ImageSearchPage({super.key, required this.controller});
final SearchPageController controller;
@@ -29,14 +28,30 @@ class ImageSearchPage extends StatefulWidget {
}
class _ImageSearchPageState extends State<ImageSearchPage> {
- final TextEditingController _urlController = TextEditingController();
- SearchPageController get _searchPageController => widget.controller;
- final ImagePicker _picker = ImagePicker();
- bool _isUrlMode = false;
+ final _urlController = TextEditingController();
+ final _urlFocus = FocusNode();
+ final _pageScroll = ScrollController();
+ final _sourceScroll = ScrollController();
+ final _resultScroll = ScrollController();
+ final _resultsKey = GlobalKey();
+ final _picker = ImagePicker();
+ Timer? _previewDebounce;
+ File? _imageFile;
String _previewUrl = '';
- Timer? _debounceTimer;
- File? _selectedImageFile;
- String? _selectedImageName;
+ String _lastUrlText = '';
+ String? _inputError;
+ bool _useUrl = false;
+ bool _isPicking = false;
+ bool _userScrolledDuringSearch = false;
+
+ SearchPageController get _controller => widget.controller;
+ bool get _busy => _controller.isImageSearching || _isPicking;
+ bool get _hasImage =>
+ _useUrl ? _parseHttpUrl(_urlController.text) != null : _imageFile != null;
+
+ Duration get _transition => MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 300);
@override
void initState() {
@@ -46,758 +61,528 @@ class _ImageSearchPageState extends State<ImageSearchPage> {
@override
void dispose() {
- _debounceTimer?.cancel();
- _urlController.removeListener(_onUrlChanged);
+ _previewDebounce?.cancel();
_urlController.dispose();
+ _urlFocus.dispose();
+ _pageScroll.dispose();
+ _sourceScroll.dispose();
+ _resultScroll.dispose();
super.dispose();
}
+ void _resetResults() {
+ _controller.clearImageSearchState();
+ _inputError = null;
+ }
+
void _onUrlChanged() {
- _debounceTimer?.cancel();
- final text = _urlController.text.trim();
- if (text.isEmpty) {
- setState(() => _previewUrl = '');
- return;
- }
- _debounceTimer = Timer(const Duration(milliseconds: 500), () {
- if (!mounted) {
- return;
- }
- setState(() {
- _searchPageController.clearImageSearchState();
- _previewUrl = text;
- });
+ final value = _urlController.text.trim();
+ // Selection changes must not invalidate a running search.
+ if (value == _lastUrlText) return;
+ _lastUrlText = value;
+ _previewDebounce?.cancel();
+ setState(() {
+ _resetResults();
+ _previewUrl = '';
+ });
+ if (_parseHttpUrl(value) == null) return;
+ _previewDebounce = Timer(const Duration(milliseconds: 500), () {
+ if (mounted) setState(() => _previewUrl = value);
});
}
- Future<void> _pickImageFile() async {
- final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
- if (image == null) return;
- const int maxImageBytes = 25 * 1024 * 1024;
- final imageFile = File(image.path);
- final imageBytes = await imageFile.length();
- if (imageBytes > maxImageBytes) {
- if (!mounted) return;
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(content: Text('图片大小不能超过 25MB')),
- );
- return;
- }
-
- if (!mounted) return;
+ void _changeSource(bool useUrl) {
+ if (_busy || _useUrl == useUrl) return;
+ _previewDebounce?.cancel();
+ _urlFocus.unfocus();
setState(() {
- _searchPageController.clearImageSearchState();
- _selectedImageFile = imageFile;
- _selectedImageName = image.name;
+ _useUrl = useUrl;
+ _resetResults();
+ _previewUrl = _parseHttpUrl(_urlController.text) != null
+ ? _urlController.text.trim()
+ : '';
});
}
- Future<void> _startSearch() async {
- if (_isUrlMode) {
- final imageUrl = _urlController.text.trim();
- final uri = Uri.tryParse(imageUrl);
- if (imageUrl.isEmpty || uri == null || !uri.hasScheme) {
- KazumiDialog.showToast(message: '请输入有效的图片链接');
+ Future<void> _pasteUrl() async {
+ if (_busy) return;
+ try {
+ final text =
+ (await Clipboard.getData(Clipboard.kTextPlain))?.text?.trim();
+ if (!mounted || _busy || !_useUrl) return;
+ if (text == null || text.isEmpty) {
+ setState(() => _inputError = '剪贴板里还没有图片链接');
return;
}
- await _searchPageController.searchImageByUrl(imageUrl);
- } else {
- final imageFile = _selectedImageFile;
- if (imageFile == null) {
- KazumiDialog.showToast(message: '请先选择图片文件');
- return;
+ _urlController.text = text;
+ if (!_hasImage) {
+ setState(() => _inputError = '请输入以 https:// 或 http:// 开头的图片链接');
}
- await _searchPageController.searchImageByFile(imageFile);
- }
-
- if (!mounted) {
- return;
- }
-
- if (_searchPageController.imageSearchError.isNotEmpty &&
- _searchPageController.imageSearchResults.isEmpty) {
- KazumiDialog.showToast(message: _searchPageController.imageSearchError);
+ } catch (_) {
+ if (mounted) setState(() => _inputError = '无法读取剪贴板,请手动粘贴链接');
}
}
- void _switchMode() {
+ Future<void> _pickImage() async {
+ if (_busy) return;
setState(() {
- _isUrlMode = !_isUrlMode;
+ _isPicking = true;
+ _inputError = null;
});
+ try {
+ final image = await _picker.pickImage(source: ImageSource.gallery);
+ if (image == null) return;
+ final file = File(image.path);
+ if (await file.length() > 25 * 1024 * 1024) {
+ if (mounted) setState(() => _inputError = '图片超过 25 MB,请换一张较小的截图');
+ return;
+ }
+ if (!mounted) return;
+ setState(() {
+ _resetResults();
+ _imageFile = file;
+ });
+ } catch (_) {
+ if (mounted) setState(() => _inputError = '无法读取图片,请重新选择并检查相册权限');
+ } finally {
+ if (mounted) setState(() => _isPicking = false);
+ }
}
- static String _formatTraceResultTitle(ResultItem result) {
- final title = result.anilist?.title;
- return title?.chinese ??
- title?.native ??
- title?.romaji ??
- title?.english ??
- result.filename ??
- '未知番剧';
- }
-
- static String _formatTraceEpisode(dynamic episode) {
- String formatEpisodeValue(num value) {
- return value % 1 == 0 ? value.toInt().toString() : value.toString();
+ Future<void> _search() async {
+ if (_busy) return;
+ if (!_hasImage) {
+ setState(() => _inputError = '请输入有效的 HTTP 或 HTTPS 图片链接');
+ _urlFocus.requestFocus();
+ return;
}
-
- if (episode is num) {
- return '第 ${formatEpisodeValue(episode)} 集';
+ _previewDebounce?.cancel();
+ FocusManager.instance.primaryFocus?.unfocus();
+ setState(() {
+ _inputError = null;
+ _userScrolledDuringSearch = false;
+ if (_useUrl) _previewUrl = _urlController.text.trim();
+ });
+ final search = _useUrl
+ ? _controller.searchImageByUrl(_urlController.text.trim())
+ : _controller.searchImageByFile(_imageFile!);
+ WidgetsBinding.instance.addPostFrameCallback((_) => _revealResults());
+ await search;
+ if (mounted && !_userScrolledDuringSearch) {
+ WidgetsBinding.instance.addPostFrameCallback((_) => _revealResults());
}
- if (episode is List && episode.isNotEmpty) {
- final episodes = episode.whereType<num>().map(formatEpisodeValue);
- if (episodes.isNotEmpty) {
- return '剧集: ${episodes.join(' / ')}';
+ }
+
+ void _revealResults() {
+ if (!mounted) return;
+ if (_resultScroll.hasClients) {
+ if (_transition == Duration.zero) {
+ _resultScroll.jumpTo(0);
+ } else {
+ _resultScroll.animateTo(0,
+ duration: _transition, curve: Curves.easeOutCubic);
+ }
+ } else {
+ final resultsContext = _resultsKey.currentContext;
+ if (resultsContext != null) {
+ Scrollable.ensureVisible(resultsContext,
+ duration: _transition, curve: Curves.easeOutCubic);
}
}
- return '剧集未知';
}
- int _resolveCrossAxisCount(double width) {
- if (width < LayoutBreakpoint.compact['width']!) {
- return 1;
- }
- if (width < LayoutBreakpoint.medium['width']!) {
- return 2;
- }
- if (width < 1180) {
- return 3;
+ Future<void> _openExternal(Uri uri) async {
+ try {
+ if (await launchUrl(uri, mode: LaunchMode.externalApplication)) return;
+ } catch (_) {
+ // Fall through to the shared error message.
}
- return 4;
+ if (!mounted) return;
+ ScaffoldMessenger.of(context).showSnackBar(
+ const SnackBar(content: Text('暂时无法打开链接,请稍后再试')),
+ );
}
- @override
- Widget build(BuildContext context) {
- final colorScheme = Theme.of(context).colorScheme;
- final textTheme = Theme.of(context).textTheme;
-
- return Scaffold(
- appBar: SysAppBar(
- backgroundColor: Colors.transparent,
- title: const Text('图片搜索'),
- ),
- body: SingleChildScrollView(
- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
- child: Center(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 1400),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- spacing: 25,
- children: [
- AnimatedSwitcher(
- duration: const Duration(milliseconds: 200),
- child: _isUrlMode
- ? _buildUrlInput(colorScheme, textTheme)
- : _buildUploadArea(colorScheme, textTheme),
- ),
- Center(
- child: TextButton.icon(
- onPressed: _switchMode,
- icon: Icon(
- _isUrlMode ? Icons.upload_file : Icons.link,
- size: 18,
- ),
- label: Text(_isUrlMode ? '改为上传图片文件' : '改为输入图片 URL'),
- ),
- ),
- Observer(
- builder: (context) => SizedBox(
- width: double.infinity,
- height: 52,
- child: FilledButton.icon(
- onPressed: _searchPageController.isImageSearching
- ? null
- : _startSearch,
- icon: _searchPageController.isImageSearching
- ? SizedBox(
- width: 18,
- height: 18,
- child: LoadingIndicator(
- color: colorScheme.onPrimary,
- ),
- )
- : const Icon(Icons.image_search_rounded),
- label: Text(
- _searchPageController.isImageSearching
- ? '搜索中...'
- : '开始搜索',
- style: const TextStyle(fontSize: 16),
- ),
- ),
- ),
- ),
- _buildResultSection(colorScheme, textTheme),
- _buildTips(colorScheme, textTheme),
- ],
- ),
+ void _showHelp() {
+ showDialog<void>(
+ context: context,
+ builder: (context) => AlertDialog(
+ icon: const Icon(Icons.image_search_rounded),
+ title: const Text('让截图更容易被找到'),
+ content: const SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 16,
+ children: [
+ Text('使用动画正片截图,保留原始比例。尽量避开黑边、字幕遮挡、水印与拼接画面。'),
+ Text('插画、漫画和经过大幅裁剪的图片通常无法匹配。相似度仅供参考,建议对照画面或预览片段确认。'),
+ Text('识别由 trace.moe 提供。开始识别后,所选图片或图片链接会发送至该服务。'),
+ ],
),
),
+ actions: [
+ TextButton(
+ onPressed: () => _openExternal(Uri.parse('https://trace.moe')),
+ child: const Text('访问 trace.moe'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('知道了')),
+ ],
),
);
}
- Widget _buildUploadArea(ColorScheme colorScheme, TextTheme textTheme) {
- return GestureDetector(
- onTap: _pickImageFile,
- child: Container(
- width: double.infinity,
- height: 240,
- decoration: BoxDecoration(
- color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
- borderRadius: BorderRadius.circular(16),
- border: Border.all(
- color: colorScheme.outline.withValues(alpha: 0.4),
- width: 1.5,
- strokeAlign: BorderSide.strokeAlignOutside,
- ),
- ),
- clipBehavior: Clip.antiAlias,
- child: _selectedImageFile == null
- ? Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Container(
- width: 64,
- height: 64,
- decoration: BoxDecoration(
- color: colorScheme.primaryContainer,
- shape: BoxShape.circle,
- ),
- child: Icon(
- Icons.add_photo_alternate_outlined,
- size: 32,
- color: colorScheme.onPrimaryContainer,
- ),
- ),
- const SizedBox(height: 16),
- Text(
- '点击选择图片',
- style: textTheme.titleMedium?.copyWith(
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 6),
- Text(
- '支持 JPG、PNG、WEBP 格式',
- style: textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- ),
- ),
- ],
- )
- : Stack(
- fit: StackFit.expand,
- children: [
- Image.file(
- _selectedImageFile!,
- fit: BoxFit.cover,
- errorBuilder: (context, error, stackTrace) => Center(
- child: Text(
- '图片预览失败',
- style: textTheme.bodyMedium?.copyWith(
- color: colorScheme.error,
- ),
- ),
- ),
- ),
- DecoratedBox(
- decoration: BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- colors: [
- Colors.black.withValues(alpha: 0.05),
- Colors.black.withValues(alpha: 0.55),
- ],
- ),
- ),
- ),
- Positioned(
- left: 16,
- right: 16,
- bottom: 16,
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Scaffold(
+ backgroundColor: colors.surface,
+ appBar: SysAppBar(
+ backgroundColor: colors.surface,
+ title: const Text('以图搜番'),
+ actions: [
+ IconButton(
+ onPressed: _showHelp,
+ tooltip: '搜图小贴士',
+ icon: const Icon(Icons.help_outline_rounded)),
+ ],
+ ),
+ body: SafeArea(
+ top: false,
+ child: NotificationListener<UserScrollNotification>(
+ onNotification: (notification) {
+ if (_controller.isImageSearching &&
+ notification.direction != ScrollDirection.idle) {
+ _userScrolledDuringSearch = true;
+ }
+ return false;
+ }, child: LayoutBuilder(builder: (context, constraints) {
+ final window = MediaQuery.sizeOf(context);
+ final textScale = MediaQuery.textScalerOf(context).scale(16) / 16;
+ final splitLayout = constraints.maxWidth >= 840 ||
+ (constraints.maxWidth >= 600 &&
+ window.width > window.height &&
+ textScale < 1.5);
+ final padding = constraints.maxWidth < 600 ? 16.0 : 24.0;
+ return Observer(builder: (context) {
+ final searching = _controller.isImageSearching;
+ final error = _controller.imageSearchError;
+ final results = _controller.imageSearchResults.toList()
+ ..sort(
+ (a, b) => (b.similarity ?? 0).compareTo(a.similarity ?? 0));
+ final showResults =
+ searching || results.isNotEmpty || error.isNotEmpty;
+ final short = constraints.maxHeight < 440;
+ // Keep the form scrollable when the keyboard consumes most of the height.
+ final pinAction = splitLayout && constraints.maxHeight >= 240;
+ final source = _buildSource(context, searching, showResults,
+ short: short, inlineAction: !pinAction);
+ final resultContent = _ImageSearchResults(
+ results: results,
+ searching: searching,
+ error: error,
+ onRetry: _hasImage ? _search : null,
+ onSelect: (title) => context.pop(title),
+ onPreview: _openExternal,
+ );
+ if (splitLayout) {
+ return Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 1440),
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(padding, 8, padding, 16),
child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ spacing: 24,
children: [
- Expanded(
+ SizedBox(
+ width:
+ ((constraints.maxWidth - padding * 2 - 24) * .36)
+ .clamp(264.0, 400.0),
child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text(
- _selectedImageName ?? '已选择图片',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: textTheme.titleMedium?.copyWith(
- color: Colors.white,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- '点击可重新选择图片',
- style: textTheme.bodySmall?.copyWith(
- color: Colors.white.withValues(alpha: 0.78),
+ Expanded(
+ child: Scrollbar(
+ controller: _sourceScroll,
+ child: SingleChildScrollView(
+ key: const PageStorageKey(
+ 'image-search-source'),
+ controller: _sourceScroll,
+ padding: const EdgeInsets.only(bottom: 16),
+ child: source,
),
- ),
+ )),
+ if (pinAction) ...[
+ const SizedBox(height: 8),
+ _buildPrimaryAction(searching),
+ ],
],
),
),
- IconButton.filledTonal(
- onPressed: _pickImageFile,
- icon: const Icon(Icons.edit_outlined),
- tooltip: '重新选择',
+ Expanded(
+ child: Material(
+ color: colors.surface,
+ borderRadius: BorderRadius.circular(28),
+ clipBehavior: Clip.antiAlias,
+ child: Scrollbar(
+ controller: _resultScroll,
+ child: SingleChildScrollView(
+ key: const PageStorageKey(
+ 'image-search-results'),
+ controller: _resultScroll,
+ padding: const EdgeInsets.all(20),
+ child: resultContent,
+ ),
+ ),
+ ),
),
],
),
),
- ],
+ ),
+ );
+ }
+ return Scrollbar(
+ controller: _pageScroll,
+ child: SingleChildScrollView(
+ key: const PageStorageKey('image-search-page'),
+ controller: _pageScroll,
+ keyboardDismissBehavior:
+ ScrollViewKeyboardDismissBehavior.onDrag,
+ padding: EdgeInsets.fromLTRB(padding, 8, padding, 24),
+ child: Center(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 640),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ spacing: 24,
+ children: [
+ source,
+ if (showResults)
+ SizedBox(key: _resultsKey, child: resultContent),
+ ],
+ ),
+ ),
+ ),
),
+ );
+ });
+ })),
),
);
}
- Widget _buildUrlInput(ColorScheme colorScheme, TextTheme textTheme) {
+ Widget _buildSource(BuildContext context, bool searching, bool showResults,
+ {required bool short, required bool inlineAction}) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ final busy = searching || _isPicking;
return Column(
- key: const ValueKey('url-input'),
- crossAxisAlignment: CrossAxisAlignment.start,
- spacing: 12,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- TextField(
- controller: _urlController,
- decoration: InputDecoration(
- hintText: '请输入图片链接',
- hintStyle: TextStyle(
- color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
- fontSize: 13,
- ),
- prefixIcon: const Icon(Icons.link),
- suffixIcon: IconButton(
- icon: const Icon(Icons.clear),
- onPressed: _urlController.clear,
- tooltip: '清除',
- ),
- filled: true,
- fillColor:
- colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(12),
- borderSide: BorderSide.none,
- ),
- focusedBorder: OutlineInputBorder(
- borderRadius: BorderRadius.circular(12),
- borderSide: BorderSide(color: colorScheme.primary, width: 1.5),
- ),
- contentPadding:
- const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
+ Semantics(
+ header: true,
+ child: Text(
+ showResults
+ ? '搜索图片'
+ : short
+ ? '用截图找到番名'
+ : '这一幕,\n出自哪部番?',
+ style:
+ (showResults || short ? type.headlineSmall : type.displaySmall)
+ ?.copyWith(
+ fontWeight: FontWeight.w700, color: colors.onSurface),
),
- keyboardType: TextInputType.url,
- textInputAction: TextInputAction.search,
- onSubmitted: (_) => _startSearch(),
),
- _buildUrlPreview(colorScheme, textTheme),
- ],
- );
- }
-
- Widget _buildUrlPreview(ColorScheme colorScheme, TextTheme textTheme) {
- return AnimatedContainer(
- duration: const Duration(milliseconds: 250),
- width: double.infinity,
- constraints: BoxConstraints(
- minHeight: 170,
- maxHeight: _previewUrl.isNotEmpty ? 300 : 170,
- ),
- decoration: BoxDecoration(
- color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
- borderRadius: BorderRadius.circular(16),
- border: Border.all(
- color: colorScheme.outline.withValues(alpha: 0.4),
- width: 1.5,
- strokeAlign: BorderSide.strokeAlignOutside,
- ),
- ),
- clipBehavior: Clip.antiAlias,
- child: _previewUrl.isEmpty
- ? Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Icon(
- Icons.image_outlined,
- size: 36,
- color: colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
- ),
- const SizedBox(height: 8),
- Text(
- '输入图片链接后预览',
- style: textTheme.bodySmall?.copyWith(
- color:
- colorScheme.onSurfaceVariant.withValues(alpha: 0.4),
- ),
- ),
- ],
- ),
- )
- : Image.network(
- _previewUrl,
- fit: BoxFit.contain,
- loadingBuilder: (context, child, loadingProgress) {
- if (loadingProgress == null) {
- return child;
- }
- final total = loadingProgress.expectedTotalBytes;
- final loaded = loadingProgress.cumulativeBytesLoaded;
- return Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- CircularProgressIndicator(
- value: total != null ? loaded / total : null,
- strokeWidth: 2.5,
- ),
- const SizedBox(height: 12),
- Text(
- '加载中...',
- style: textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- ),
- ),
- ],
- ),
- );
- },
- errorBuilder: (context, error, stackTrace) => Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: [
- Icon(
- Icons.broken_image_outlined,
- size: 36,
- color: colorScheme.error.withValues(alpha: 0.7),
- ),
- const SizedBox(height: 8),
- Text(
- '图片加载失败',
- style: textTheme.bodySmall?.copyWith(
- color: colorScheme.error,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- '请检查链接是否有效',
- style: textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- ),
- ),
- ],
- ),
- ),
- ),
- );
- }
-
- Widget _buildResultSection(ColorScheme colorScheme, TextTheme textTheme) {
- return Observer(
- builder: (context) {
- final results = _searchPageController.imageSearchResults;
- final errorMessage = _searchPageController.imageSearchError;
-
- if (_searchPageController.isImageSearching) {
- return _buildStateCard(
- colorScheme: colorScheme,
- textTheme: textTheme,
- icon: const SizedBox(
- width: 28,
- height: 28,
- child: LoadingIndicator(),
- ),
- title: '正在识别图片',
- description: '请稍候,正在从截图中匹配番剧信息',
- );
- }
-
- if (results.isEmpty) {
- return _buildStateCard(
- colorScheme: colorScheme,
- textTheme: textTheme,
- icon: Icon(
- errorMessage.isEmpty
- ? Icons.grid_view_rounded
- : Icons.error_outline,
- size: 30,
- color: errorMessage.isEmpty
- ? colorScheme.primary
- : colorScheme.error,
- ),
- title: errorMessage.isEmpty ? '搜索结果将在这里展示' : '未获取到搜索结果',
- description:
- errorMessage.isEmpty ? '选择图片文件或输入图片链接后开始搜索' : errorMessage,
- );
- }
-
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- '识别结果',
- style: textTheme.titleLarge?.copyWith(
- fontWeight: FontWeight.w700,
+ if (!showResults && !short) ...[
+ const SizedBox(height: 8),
+ Text('用一张截图,找到番名与出现的集数。',
+ style: type.bodyLarge?.copyWith(color: colors.onSurfaceVariant)),
+ ],
+ SizedBox(height: short ? 12 : 24),
+ _ImageSourceSelector(
+ useUrl: _useUrl, enabled: !busy, onChanged: _changeSource),
+ const SizedBox(height: 16),
+ if (_useUrl) ...[
+ TextField(
+ controller: _urlController,
+ focusNode: _urlFocus,
+ readOnly: busy,
+ keyboardType: TextInputType.url,
+ textInputAction: TextInputAction.search,
+ autocorrect: false,
+ enableSuggestions: false,
+ onSubmitted: (_) => _search(),
+ onTapOutside: (_) => _urlFocus.unfocus(),
+ decoration: InputDecoration(
+ labelText: '图片链接',
+ hintText: 'https://…',
+ filled: true,
+ fillColor: colors.surfaceContainerLow,
+ border:
+ OutlineInputBorder(borderRadius: BorderRadius.circular(16)),
+ suffixIcon: IconButton(
+ onPressed: busy ? null : _pasteUrl,
+ tooltip: '粘贴图片链接',
+ icon: const Icon(Icons.content_paste_rounded),
),
),
+ ),
+ const SizedBox(height: 8),
+ Text('使用可直接访问的 HTTP 或 HTTPS 图片地址',
+ style: type.bodySmall?.copyWith(color: colors.onSurfaceVariant)),
+ if (_previewUrl.isNotEmpty) ...[
const SizedBox(height: 16),
- LayoutBuilder(
- builder: (context, constraints) {
- final crossAxisCount = _resolveCrossAxisCount(
- constraints.maxWidth,
- );
- return GridView.builder(
- shrinkWrap: true,
- physics: const NeverScrollableScrollPhysics(),
- itemCount: results.length,
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: crossAxisCount,
- crossAxisSpacing: 16,
- mainAxisSpacing: 16,
- mainAxisExtent: 152,
- ),
- itemBuilder: (context, index) {
- final result = results[index];
- return InkWell(
- onTap: () {
- final title = _formatTraceResultTitle(result);
- context.pop(title);
- },
- child: _buildResultCard(
- context,
- colorScheme,
- textTheme,
- result,
- ),
- );
- },
- );
- },
- ),
+ _buildPreview(short: short),
],
- );
- },
- );
- }
-
- Widget _buildStateCard({
- required ColorScheme colorScheme,
- required TextTheme textTheme,
- required Widget icon,
- required String title,
- required String description,
- }) {
- return Container(
- width: double.infinity,
- padding: const EdgeInsets.all(24),
- decoration: BoxDecoration(
- color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.35),
- borderRadius: BorderRadius.circular(16),
- ),
- child: Column(
- children: [
- icon,
- const SizedBox(height: 14),
- Text(
- title,
- style: textTheme.titleMedium?.copyWith(
- fontWeight: FontWeight.w700,
+ ] else ...[
+ if (_imageFile != null)
+ _buildPreview(short: short)
+ else
+ Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: 16, vertical: short ? 12 : 24),
+ child: short
+ ? Row(children: [
+ const _ImageSearchEmblem(size: 48),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text('截图预览',
+ style: type.titleMedium
+ ?.copyWith(color: colors.onSurfaceVariant))),
+ ])
+ : Column(
+ children: [
+ const _ImageSearchEmblem(size: 72),
+ const SizedBox(height: 12),
+ Text('截图预览',
+ textAlign: TextAlign.center,
+ style: type.titleMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ],
+ ),
),
- ),
const SizedBox(height: 8),
- Text(
- description,
- textAlign: TextAlign.center,
- style: textTheme.bodyMedium?.copyWith(
- color: colorScheme.onSurfaceVariant,
- height: 1.5,
- ),
- ),
- ],
- ),
- );
- }
-
- Widget _buildResultCard(
- BuildContext context,
- ColorScheme colorScheme,
- TextTheme textTheme,
- ResultItem result,
- ) {
- final coverUrl = result.image ??
- result.anilist?.coverImage?.large ??
- result.anilist?.coverImage?.medium;
-
- return Container(
- padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
- decoration: BoxDecoration(
- color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
- borderRadius: BorderRadius.circular(16),
- border: Border.all(
- color: colorScheme.outline.withValues(alpha: 0.16),
- ),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- _formatTraceResultTitle(result),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: textTheme.titleMedium?.copyWith(
- fontWeight: FontWeight.w700,
- ),
- ),
- const SizedBox(height: 10),
- Expanded(
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- spacing: 5,
+ if (_imageFile != null)
+ Row(
children: [
- SizedBox(
- child: AspectRatio(
- aspectRatio: 16 / 9,
- child: NetworkImgLayer(
- src: coverUrl,
- width: 132,
- height: 74.25,
- ),
- ),
- ),
Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _buildInfoLine(
- textTheme,
- colorScheme,
- _formatTraceEpisode(result.episode),
- ),
- _buildInfoLine(
- textTheme,
- colorScheme,
- '相似度: ${formatTraceSimilarity(result.similarity)}',
- ),
- _buildInfoLine(
- textTheme,
- colorScheme,
- '时间: ${durationToString(Duration(seconds: (result.from ?? 0).floor()))} - ${durationToString(Duration(seconds: (result.to ?? 0).floor()))}',
- ),
- ],
- ),
- ),
+ child: Text(path.basename(_imageFile!.path),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: type.bodySmall
+ ?.copyWith(color: colors.onSurfaceVariant))),
+ TextButton.icon(
+ onPressed: busy ? null : _pickImage,
+ label: const Text('更换截图'),
+ icon: const Icon(Icons.swap_horiz_rounded, size: 20)),
],
- ),
+ )
+ else
+ Text('JPG、PNG、WebP · 最大 25 MB',
+ textAlign: TextAlign.center,
+ style:
+ type.bodySmall?.copyWith(color: colors.onSurfaceVariant)),
+ ],
+ if (_inputError != null) ...[
+ const SizedBox(height: 12),
+ Semantics(
+ liveRegion: true,
+ child: Text(_inputError!,
+ style: type.bodyMedium?.copyWith(color: colors.error))),
+ ],
+ const SizedBox(height: 16),
+ if (inlineAction) _buildPrimaryAction(searching),
+ const SizedBox(height: 12),
+ Text('由 trace.moe 识别动画截图',
+ textAlign: TextAlign.center,
+ style: type.bodySmall?.copyWith(color: colors.onSurfaceVariant)),
+ if (!showResults && !short) ...[
+ const SizedBox(height: 24),
+ const _ImageSearchTip(
+ icon: Icons.aspect_ratio_rounded,
+ title: '保留完整画面,识别更准确',
+ description: '保持原始比例,尽量避开黑边、水印和拼图。',
),
],
- ),
+ ],
);
}
- Widget _buildInfoLine(
- TextTheme textTheme,
- ColorScheme colorScheme,
- String value,
- ) {
- return Text(
- value,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: textTheme.bodyMedium?.copyWith(
- color: colorScheme.onSurfaceVariant,
- fontWeight: FontWeight.w600,
+ Widget _buildPrimaryAction(bool searching) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ final busy = searching || _isPicking;
+ final selecting = !_useUrl && _imageFile == null;
+ return FilledButton.icon(
+ key: const ValueKey('image-search-primary'),
+ onPressed: busy
+ ? null
+ : selecting
+ ? _pickImage
+ : _hasImage
+ ? _search
+ : null,
+ style: ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size.fromHeight(56)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 24, vertical: 16)),
+ textStyle: WidgetStatePropertyAll(
+ type.titleMedium?.copyWith(fontWeight: FontWeight.w700)),
+ shape: WidgetStateProperty.resolveWith((states) =>
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ states.contains(WidgetState.pressed) ? 16 : 28))),
+ animationDuration: _transition,
),
+ icon: searching || _isPicking
+ ? LoadingIndicator(size: 24, color: colors.onSurfaceVariant)
+ : Icon(_hasImage
+ ? Icons.image_search_rounded
+ : Icons.add_photo_alternate_outlined),
+ label: Text(searching
+ ? '正在识别'
+ : _isPicking
+ ? '正在读取图片'
+ : selecting
+ ? '选择截图'
+ : _useUrl
+ ? '开始识别'
+ : '识别这张截图'),
);
}
- Widget _buildTips(ColorScheme colorScheme, TextTheme textTheme) {
- final baseStyle = textTheme.bodySmall?.copyWith(
- color: colorScheme.onSurfaceVariant,
- height: 1.5,
- );
- final linkStyle = baseStyle?.copyWith(
- color: colorScheme.primary,
- decoration: TextDecoration.underline,
- decorationColor: colorScheme.primary,
- );
- final dotColor = colorScheme.onSurfaceVariant.withValues(alpha: 0.6);
-
- final tips = <Widget>[
- Text('仅支持使用原始比例番剧截图搜索结果', style: baseStyle),
- Text('截图应清晰,避免过度压缩或添加水印', style: baseStyle),
- RichText(
- text: TextSpan(
- style: baseStyle,
- children: [
- const TextSpan(text: '搜索引擎由 '),
- WidgetSpan(
- alignment: PlaceholderAlignment.baseline,
- baseline: TextBaseline.alphabetic,
- child: GestureDetector(
- onTap: () => launchUrl(
- Uri.parse('https://trace.moe'),
- mode: LaunchMode.externalApplication,
- ),
- child: Text('trace.moe', style: linkStyle),
- ),
- ),
- const TextSpan(text: ' 提供支持'),
- ],
- ),
+ Widget _buildPreview({required bool short}) {
+ final colors = Theme.of(context).colorScheme;
+ Widget fallback(BuildContext context, Object error, StackTrace? stack) =>
+ const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: Text('暂时无法预览\n仍可尝试识别,或更换图片', textAlign: TextAlign.center),
+ ));
+ return Semantics(
+ label: '待识别的完整截图',
+ image: true,
+ child: Container(
+ height: short ? 136 : 208,
+ clipBehavior: Clip.antiAlias,
+ decoration: BoxDecoration(
+ color: colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(24)),
+ child: _useUrl
+ ? Image.network(_previewUrl,
+ fit: BoxFit.contain,
+ errorBuilder: fallback,
+ loadingBuilder: (context, child, progress) => progress == null
+ ? child
+ : const Center(
+ child: LoadingIndicator(semanticsLabel: '正在加载截图')))
+ : Image.file(_imageFile!,
+ fit: BoxFit.contain, errorBuilder: fallback),
),
- ];
-
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Icon(
- Icons.info_outline,
- size: 16,
- color: colorScheme.onSurfaceVariant,
- ),
- const SizedBox(width: 6),
- Text(
- '以图搜番',
- style: textTheme.labelLarge?.copyWith(
- color: colorScheme.onSurfaceVariant,
- fontWeight: FontWeight.w600,
- ),
- ),
- ],
- ),
- const SizedBox(height: 10),
- ...tips.map(
- (tipWidget) => Padding(
- padding: const EdgeInsets.only(bottom: 6),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Padding(
- padding: const EdgeInsets.only(top: 5),
- child: Container(
- width: 4,
- height: 4,
- decoration: BoxDecoration(
- color: dotColor,
- shape: BoxShape.circle,
- ),
- ),
- ),
- const SizedBox(width: 8),
- Expanded(child: tipWidget),
- ],
- ),
- ),
- ),
- ],
);
}
}
diff --git a/lib/pages/search/image_search_widgets.dart b/lib/pages/search/image_search_widgets.dart
new file mode 100644
index 00000000..9aa6611d
--- /dev/null
+++ b/lib/pages/search/image_search_widgets.dart
@@ -0,0 +1,555 @@
+part of 'image_search_page.dart';
+
+class _ImageSourceSelector extends StatelessWidget {
+ const _ImageSourceSelector(
+ {required this.useUrl, required this.enabled, required this.onChanged});
+ final bool useUrl;
+ final bool enabled;
+ final ValueChanged<bool> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Row(
+ spacing: 4,
+ children: [false, true].map((url) {
+ final selected = url == useUrl;
+ return Expanded(
+ child: Semantics(
+ selected: selected,
+ inMutuallyExclusiveGroup: true,
+ child: FilledButton(
+ onPressed: enabled ? () => onChanged(url) : null,
+ style: ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size(0, 48)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 12, vertical: 12)),
+ backgroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? colors.onSurface.withValues(alpha: .12)
+ : selected
+ ? colors.secondaryContainer
+ : colors.surfaceContainerHighest),
+ foregroundColor: WidgetStateProperty.resolveWith(
+ (states) => states.contains(WidgetState.disabled)
+ ? colors.onSurface.withValues(alpha: .38)
+ : selected
+ ? colors.onSecondaryContainer
+ : colors.onSurfaceVariant),
+ shape: WidgetStateProperty.resolveWith((states) {
+ if (states.contains(WidgetState.pressed)) {
+ return RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12));
+ }
+ return RoundedRectangleBorder(
+ borderRadius: selected
+ ? BorderRadius.circular(24)
+ : BorderRadius.horizontal(
+ left: Radius.circular(url ? 8 : 24),
+ right: Radius.circular(url ? 24 : 8)));
+ }),
+ animationDuration: MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 200),
+ ),
+ child: Wrap(
+ alignment: WrapAlignment.center,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ spacing: 8,
+ runSpacing: 4,
+ children: [
+ Icon(
+ selected
+ ? Icons.check_rounded
+ : url
+ ? Icons.link_rounded
+ : Icons.photo_library_outlined,
+ size: 20),
+ Text(url ? '图片链接' : '本地图片'),
+ ]),
+ ),
+ ));
+ }).toList());
+ }
+}
+
+class _ImageSearchEmblem extends StatelessWidget {
+ const _ImageSearchEmblem({required this.size});
+ final double size;
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return ExcludeSemantics(
+ child: ClipPath(
+ clipper: const _SearchShapeClipper(),
+ child: ColoredBox(
+ color: colors.primaryContainer,
+ child: SizedBox.square(
+ dimension: size,
+ child: Icon(Icons.image_search_rounded,
+ size: size * .44, color: colors.onPrimaryContainer))),
+ ));
+ }
+}
+
+class _SearchShapeClipper extends CustomClipper<Path> {
+ const _SearchShapeClipper();
+ static final _path = MaterialShapes.cookie4Sided.toPath();
+ @override
+ Path getClip(Size size) => _path
+ .transform(Matrix4.diagonal3Values(size.width, size.height, 1).storage);
+ @override
+ bool shouldReclip(_SearchShapeClipper oldClipper) => false;
+}
+
+class _ImageSearchTip extends StatelessWidget {
+ const _ImageSearchTip(
+ {required this.icon, required this.title, required this.description});
+ final IconData icon;
+ final String title;
+ final String description;
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Icon(icon, size: 24, color: colors.primary),
+ const SizedBox(width: 12),
+ Expanded(
+ child:
+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(title, style: type.titleSmall),
+ const SizedBox(height: 4),
+ Text(description,
+ style: type.bodyMedium?.copyWith(color: colors.onSurfaceVariant)),
+ ])),
+ ]);
+ }
+}
+
+class _ImageSearchResults extends StatelessWidget {
+ const _ImageSearchResults(
+ {required this.results,
+ required this.searching,
+ required this.error,
+ required this.onRetry,
+ required this.onSelect,
+ required this.onPreview});
+ final List<ResultItem> results;
+ final bool searching;
+ final String error;
+ final VoidCallback? onRetry;
+ final ValueChanged<String> onSelect;
+ final ValueChanged<Uri> onPreview;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ if (searching) {
+ return const _ResultStatus(
+ icon: LoadingIndicator(size: 72, semanticsLabel: '正在匹配动画画面'),
+ title: '正在寻找这一幕',
+ description: '正在比对动画画面,匹配番名、集数与时间。\n请稍等片刻。',
+ );
+ }
+ if (results.isEmpty && error.isEmpty) {
+ return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ const SizedBox(height: 12),
+ Text('让画面接上故事',
+ style: type.headlineMedium?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 8),
+ Text('选好截图,剩下的交给识别。',
+ style: type.bodyLarge?.copyWith(color: colors.onSurfaceVariant)),
+ const SizedBox(height: 28),
+ ...[
+ (Icons.movie_outlined, '找到番名', '从动画正片中匹配候选作品'),
+ (Icons.schedule_rounded, '定位这一幕', '查看画面所在的集数与时间'),
+ (Icons.manage_search_rounded, '继续找番', '确认结果后,直接搜索这部番'),
+ ].indexed.map((entry) => Container(
+ padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 20),
+ decoration: BoxDecoration(
+ border: entry.$1 == 2
+ ? null
+ : Border(bottom: BorderSide(color: colors.outlineVariant)),
+ ),
+ child: _ImageSearchTip(
+ icon: entry.$2.$1,
+ title: entry.$2.$2,
+ description: entry.$2.$3),
+ )),
+ ]);
+ }
+ if (results.isEmpty) {
+ final noMatch = error == '未找到匹配结果';
+ return _ResultStatus(
+ icon: Icon(
+ noMatch
+ ? Icons.image_not_supported_outlined
+ : Icons.wifi_off_rounded,
+ size: 48,
+ color: noMatch ? colors.onSurfaceVariant : colors.error),
+ title: noMatch ? '还没找到这一幕' : '这次识别未完成',
+ description: noMatch ? '试试同一场景的另一张截图,\n保留完整画面与原始比例。' : error,
+ action: onRetry == null
+ ? null
+ : FilledButton.tonalIcon(
+ onPressed: onRetry,
+ icon: const Icon(Icons.refresh_rounded),
+ label: const Text('重新识别')),
+ );
+ }
+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Semantics(
+ header: true,
+ liveRegion: true,
+ child: Text('找到 ${results.length} 个相似片段',
+ style:
+ type.headlineSmall?.copyWith(fontWeight: FontWeight.w700))),
+ const SizedBox(height: 6),
+ Text('按画面相似度排序,先对照截图再确认。',
+ style: type.bodyMedium?.copyWith(color: colors.onSurfaceVariant)),
+ if (error.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ Text(error, style: type.bodyMedium?.copyWith(color: colors.error)),
+ ],
+ const SizedBox(height: 20),
+ _BestMatch(
+ result: results.first, onSelect: onSelect, onPreview: onPreview),
+ if (results.length > 1) ...[
+ const SizedBox(height: 28),
+ Text('其他相似片段',
+ style: type.titleMedium?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 12),
+ ...results.skip(1).indexed.map((entry) => Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: _OtherMatch(
+ result: entry.$2,
+ first: entry.$1 == 0,
+ last: entry.$1 == results.length - 2,
+ onSelect: onSelect),
+ )),
+ ],
+ ]);
+ }
+}
+
+class _ResultStatus extends StatelessWidget {
+ const _ResultStatus(
+ {required this.icon,
+ required this.title,
+ required this.description,
+ this.action});
+ final Widget icon;
+ final String title;
+ final String description;
+ final Widget? action;
+ @override
+ Widget build(BuildContext context) {
+ final type = Theme.of(context).textTheme;
+ return Semantics(
+ liveRegion: true,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 32),
+ child: Column(children: [
+ icon,
+ const SizedBox(height: 24),
+ Text(title,
+ textAlign: TextAlign.center,
+ style:
+ type.headlineSmall?.copyWith(fontWeight: FontWeight.w700)),
+ const SizedBox(height: 12),
+ Text(description,
+ textAlign: TextAlign.center,
+ style: type.bodyLarge?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant)),
+ if (action != null) ...[const SizedBox(height: 24), action!],
+ ]),
+ ));
+ }
+}
+
+class _BestMatch extends StatelessWidget {
+ const _BestMatch(
+ {required this.result, required this.onSelect, required this.onPreview});
+ final ResultItem result;
+ final ValueChanged<String> onSelect;
+ final ValueChanged<Uri> onPreview;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ final similarity = result.similarity;
+ final lowSimilarity =
+ similarity == null || !similarity.isFinite || similarity < .87;
+ final video = _parseHttpUrl(result.video ?? '');
+ final details = Padding(
+ padding: const EdgeInsets.all(20),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Wrap(spacing: 8, runSpacing: 8, children: [
+ _Metadata(
+ icon: Icons.movie_outlined, label: _episode(result.episode)),
+ _Metadata(icon: Icons.schedule_rounded, label: _timeRange(result)),
+ ]),
+ if (lowSimilarity) ...[
+ const SizedBox(height: 12),
+ Text('相似度偏低,建议对照画面,或换一张截图。',
+ style: type.bodyMedium?.copyWith(color: colors.onSurface)),
+ ],
+ const SizedBox(height: 16),
+ Wrap(spacing: 8, runSpacing: 8, children: [
+ FilledButton.icon(
+ onPressed: () => onSelect(_title(result)),
+ style: FilledButton.styleFrom(minimumSize: const Size(0, 48)),
+ icon: const Icon(Icons.search_rounded, size: 20),
+ label: const Text('搜索这部番'),
+ ),
+ if (video != null)
+ OutlinedButton.icon(
+ onPressed: () => onPreview(video),
+ style: OutlinedButton.styleFrom(
+ foregroundColor: colors.onSurface,
+ side: BorderSide(color: colors.onSurface.withValues(alpha: .5)),
+ minimumSize: const Size(0, 48),
+ ),
+ icon: const Icon(Icons.play_arrow_rounded, size: 20),
+ label: const Text('预览片段'),
+ ),
+ ]),
+ ]),
+ );
+ final frame = ClipRRect(
+ borderRadius: BorderRadius.circular(16),
+ child: SizedBox(
+ height: MediaQuery.sizeOf(context).height < 500 ? 112 : 200,
+ child: _TraceFrame(result: result),
+ ),
+ );
+ return Material(
+ color: colors.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(24),
+ side: BorderSide(color: colors.outlineVariant),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
+ Padding(
+ padding: const EdgeInsets.all(20),
+ child:
+ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Wrap(
+ spacing: 12,
+ runSpacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Text('相似度最高',
+ style:
+ type.labelLarge?.copyWith(color: colors.onSurface)),
+ Text('${_similarity(result)} 相似',
+ style: type.titleMedium?.copyWith(
+ color: colors.onSurface,
+ fontWeight: FontWeight.w700)),
+ ]),
+ const SizedBox(height: 8),
+ Text(_title(result),
+ style: type.headlineSmall?.copyWith(
+ color: colors.onSurface, fontWeight: FontWeight.w700)),
+ ]),
+ ),
+ LayoutBuilder(builder: (context, constraints) {
+ if (constraints.maxWidth >= 600) {
+ return Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.only(left: 12, bottom: 12),
+ child: frame)),
+ Expanded(child: details),
+ ]);
+ }
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: frame),
+ details,
+ ]);
+ }),
+ ]),
+ );
+ }
+}
+
+class _OtherMatch extends StatelessWidget {
+ const _OtherMatch(
+ {required this.result,
+ required this.first,
+ required this.last,
+ required this.onSelect});
+ final ResultItem result;
+ final bool first;
+ final bool last;
+ final ValueChanged<String> onSelect;
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ final type = Theme.of(context).textTheme;
+ return Material(
+ color: colors.surface,
+ borderRadius: BorderRadius.vertical(
+ top: Radius.circular(first ? 20 : 8),
+ bottom: Radius.circular(last ? 20 : 8)),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => onSelect(_title(result)),
+ child: Semantics(
+ button: true,
+ label: '搜索 ${_title(result)}',
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: LayoutBuilder(
+ builder: (context, constraints) => Row(children: [
+ if (constraints.maxWidth >= 300 &&
+ MediaQuery.textScalerOf(context).scale(16) < 24) ...[
+ SizedBox(
+ width: constraints.maxWidth >= 400 ? 112 : 80,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(12),
+ child: _TraceFrame(result: result))),
+ const SizedBox(width: 16),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(_title(result),
+ maxLines: 3,
+ overflow: TextOverflow.ellipsis,
+ style: type.titleMedium
+ ?.copyWith(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 6),
+ Text(
+ '${_episode(result.episode)} · ${_similarity(result)} 相似',
+ style: type.bodyMedium
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ const SizedBox(height: 4),
+ Text(_timeRange(result),
+ style: type.bodySmall
+ ?.copyWith(color: colors.onSurfaceVariant)),
+ ])),
+ const SizedBox(width: 8),
+ Icon(Icons.arrow_outward_rounded,
+ size: 20, color: colors.onSurfaceVariant),
+ ])),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _Metadata extends StatelessWidget {
+ const _Metadata({required this.icon, required this.label});
+ final IconData icon;
+ final String label;
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
+ child: Text.rich(
+ TextSpan(children: [
+ WidgetSpan(
+ alignment: PlaceholderAlignment.middle,
+ child: Icon(icon, size: 16, color: colors.onSurface)),
+ TextSpan(text: ' $label'),
+ ]),
+ style: Theme.of(context)
+ .textTheme
+ .labelLarge
+ ?.copyWith(color: colors.onSurface)),
+ );
+ }
+}
+
+class _TraceFrame extends StatelessWidget {
+ const _TraceFrame({required this.result});
+ final ResultItem result;
+ @override
+ Widget build(BuildContext context) {
+ final source = result.image;
+ final colors = Theme.of(context).colorScheme;
+ final placeholder = Center(
+ child: Icon(Icons.movie_outlined,
+ size: 40, color: colors.onSurfaceVariant));
+ return AspectRatio(
+ aspectRatio: 16 / 9,
+ child: ColoredBox(
+ color: colors.surfaceContainerLow,
+ child: source == null || source.isEmpty
+ ? placeholder
+ : Image.network(source,
+ fit: BoxFit.contain,
+ semanticLabel: '${_title(result)}的匹配画面',
+ errorBuilder: (context, error, stack) => placeholder,
+ loadingBuilder: (context, child, progress) =>
+ progress == null ? child : placeholder),
+ ));
+ }
+}
+
+String _title(ResultItem result) {
+ final title = result.anilist?.title;
+ for (final value in [
+ title?.chinese,
+ title?.native,
+ title?.romaji,
+ title?.english,
+ result.filename
+ ]) {
+ if (value != null && value.trim().isNotEmpty) return value.trim();
+ }
+ return '未知番剧';
+}
+
+String _episode(dynamic value) {
+ String number(num n) => n % 1 == 0 ? n.toInt().toString() : n.toString();
+ if (value is num && value.isFinite) return '第 ${number(value)} 集';
+ if (value is List) {
+ final numbers =
+ value.whereType<num>().where((n) => n.isFinite).map(number).toList();
+ if (numbers.isNotEmpty) return '第 ${numbers.join(' / ')} 集';
+ }
+ return '集数未知';
+}
+
+String _similarity(ResultItem result) {
+ final value = result.similarity;
+ return value == null || !value.isFinite
+ ? '未知'
+ : '${(value.clamp(0, 1) * 100).toStringAsFixed(1)}%';
+}
+
+String _timeRange(ResultItem result) {
+ String time(double value) {
+ final seconds = value.floor();
+ final minutes = seconds ~/ 60;
+ return '${minutes.toString().padLeft(2, '0')}:${(seconds % 60).toString().padLeft(2, '0')}';
+ }
+
+ final from = result.from ?? result.at;
+ final to = result.to;
+ if (from == null || !from.isFinite || from < 0) return '时间未知';
+ if (to == null || !to.isFinite || to < from) return time(from);
+ return '${time(from)} – ${time(to)}';
+}
+
+Uri? _parseHttpUrl(String value) {
+ final uri = Uri.tryParse(value.trim());
+ return uri != null &&
+ (uri.scheme == 'https' || uri.scheme == 'http') &&
+ uri.host.isNotEmpty
+ ? uri
+ : null;
+}
diff --git a/lib/pages/search/search_page.dart b/lib/pages/search/search_page.dart
index 1b72b7e6..759d19bd 100644
--- a/lib/pages/search/search_page.dart
+++ b/lib/pages/search/search_page.dart
@@ -261,7 +261,7 @@ class _SearchPageState extends State<SearchPage> {
),
barTrailing: [
IconButton(
- tooltip: '图片搜索',
+ tooltip: '以图搜番',
onPressed: () async {
final result = await context.pushNamed('/search/image');
if (result is String && result.isNotEmpty) {
diff --git a/lib/utils/format.dart b/lib/utils/format.dart
index 5f587eb3..5a4f88f0 100644
--- a/lib/utils/format.dart
+++ b/lib/utils/format.dart
@@ -25,14 +25,3 @@ String durationToString(Duration duration) {
}
return '$hours:$minutes:$seconds';
}
-
-String formatTraceSimilarity(
- double? similarity, {
- int fractionDigits = 1,
- String empty = '--',
-}) {
- if (similarity == null) {
- return empty;
- }
- return '${(similarity * 100).toStringAsFixed(fractionDigits)}%';
-}