diff --git a/CHANGELOG.md b/CHANGELOG.md index e0d325e..96fc247 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # 更新日志 +## 1.2.3 + +- 修复下载页展开后灰屏,简化专辑任务状态与操作。 +- 减少启动日志开销,缓解资料加载卡顿。 +- 修复下架内容反复重试,以及更新、订阅和评论加载异常。 +- 修复 Android 外部目录音频打开与后台下载异常。 +- 优化返回动画,播放界面支持平滑缩回常驻播放栏。 + ## 1.2.2 - 完善发现、分类、榜单、主播与专辑浏览。 diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 9441aa3..18dfb4a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -40,10 +40,6 @@ - + diff --git a/android/app/src/main/kotlin/teikengstudio/xmplus/MainActivity.kt b/android/app/src/main/kotlin/teikengstudio/xmplus/MainActivity.kt index 11e3b97..6c889d3 100644 --- a/android/app/src/main/kotlin/teikengstudio/xmplus/MainActivity.kt +++ b/android/app/src/main/kotlin/teikengstudio/xmplus/MainActivity.kt @@ -1,18 +1,9 @@ package teikengstudio.xmplus -import android.Manifest -import android.app.NotificationManager -import android.content.pm.PackageManager import android.net.Uri -import android.os.Build -import android.os.Bundle -import android.os.Handler -import android.os.Looper -import android.os.PowerManager -import android.os.ResultReceiver import android.provider.Settings import android.provider.DocumentsContract -import android.widget.Toast +import android.content.ClipData import android.content.Intent import android.os.StatFs import android.system.ErrnoException @@ -32,8 +23,6 @@ import java.io.OutputStream import java.util.concurrent.atomic.AtomicBoolean class MainActivity : AudioServiceActivity() { - private var notificationPermissionResult: MethodChannel.Result? = null - private val notificationPermissionRequest = 2102 private val logExportRequest = 2103 private var pendingLogExport: LogExport? = null private val updatePermissionRequest = 2104 @@ -73,11 +62,22 @@ class MainActivity : AudioServiceActivity() { result.success(StatFs(File(path).canonicalPath).availableBytes) } "openAudioFile" -> { - val file = File(requireNotNull(call.argument("path"))).canonicalFile - require(file.isFile) { "Audio file does not exist" } - val uri = FileProvider.getUriForFile(this, "$packageName.files", file) + val path = requireNotNull(call.argument("path")) + val requested = Uri.parse(path) + val uri = if (requested.scheme == "content") { + requested + } else { + val file = (if (requested.scheme == "file") File(requireNotNull(requested.path)) else File(path)).canonicalFile + require(file.isFile && file.canRead()) { "Audio file does not exist or is not readable" } + try { + FileProvider.getUriForFile(this, "$packageName.files", file) + } catch (_: IllegalArgumentException) { + SharedAudioProvider.uriForFile(this, file) + } + } val intent = Intent(Intent.ACTION_VIEW).apply { setDataAndType(uri, "audio/*") + clipData = ClipData.newRawUri("audio", uri) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } startActivity(Intent.createChooser(intent, "打开音频")) @@ -172,77 +172,6 @@ class MainActivity : AudioServiceActivity() { } } } - DownloadForegroundService.messenger = flutterEngine.dartExecutor.binaryMessenger - MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DownloadForegroundService.CHANNEL) - .setMethodCallHandler { call, result -> - try { - when (call.method) { - "downloadNotificationPermission" -> { - val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - getSystemService(NotificationManager::class.java).areNotificationsEnabled() - } else true - if (enabled || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || - call.argument("request") != true) { - result.success(enabled) - } else if (notificationPermissionResult != null) { - result.error("permission_pending", "通知权限请求尚未结束", null) - } else { - notificationPermissionResult = result - requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), notificationPermissionRequest) - } - } - "downloadForeground" -> { - val intent = Intent(this, DownloadForegroundService::class.java).apply { - putExtra("title", requireNotNull(call.argument("title"))) - putExtra("text", requireNotNull(call.argument("text"))) - putExtra("receivedBytes", requireNotNull(call.argument("receivedBytes")).toLong()) - putExtra("totalBytes", call.argument("totalBytes")?.toLong() ?: 0L) - } - val service = DownloadForegroundService.instance - if (service != null) { - service.update(intent) - result.success(null) - } else { - intent.putExtra("reply", object : ResultReceiver(Handler(Looper.getMainLooper())) { - override fun onReceiveResult(code: Int, data: Bundle?) { - if (code == 0) result.success(null) - else result.error("download_foreground", data?.getString("error"), null) - } - }) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(intent) - else startService(intent) - } - } - "stopDownloadForeground" -> { - val service = DownloadForegroundService.instance - if (service != null) { - service.stopPresenting { result.success(null) } - } else { - stopService(Intent(this, DownloadForegroundService::class.java)) - result.success(null) - } - } - "batteryOptimizationExempt" -> result.success( - getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(packageName) - ) - "requestBatteryOptimizationExemption" -> { - startActivity(Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, - Uri.parse("package:$packageName"))) - result.success(null) - } - "showDownloadBackgroundError" -> { - Toast.makeText(applicationContext, call.argument("message"), Toast.LENGTH_LONG).show() - result.success(null) - } - else -> result.notImplemented() - } - } catch (error: Exception) { - if (call.method == "downloadForeground") { - Toast.makeText(applicationContext, "下载后台服务启动失败,请保持应用在前台:${error.message}", Toast.LENGTH_LONG).show() - } - result.error("android_background", error.message, null) - } - } } private fun openUpdateInstaller(file: File) { @@ -443,19 +372,7 @@ class MainActivity : AudioServiceActivity() { }.start() } - override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { - super.onRequestPermissionsResult(requestCode, permissions, grantResults) - if (requestCode == notificationPermissionRequest) { - notificationPermissionResult?.success( - grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED - ) - notificationPermissionResult = null - } - } - override fun onDestroy() { - notificationPermissionResult?.success(false) - notificationPermissionResult = null pendingUpdate?.second?.error("update_install", "安装授权已中断,请重试", null) pendingUpdate = null pendingLogExport?.let { diff --git a/android/app/src/main/kotlin/teikengstudio/xmplus/SharedAudioProvider.kt b/android/app/src/main/kotlin/teikengstudio/xmplus/SharedAudioProvider.kt new file mode 100644 index 0000000..5b1a682 --- /dev/null +++ b/android/app/src/main/kotlin/teikengstudio/xmplus/SharedAudioProvider.kt @@ -0,0 +1,78 @@ +package teikengstudio.xmplus + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.database.MatrixCursor +import android.net.Uri +import android.os.ParcelFileDescriptor +import android.util.Base64 +import android.provider.OpenableColumns +import java.io.File +import java.io.FileNotFoundException +import java.security.MessageDigest + +/** Shares only individual files explicitly opened by this app, never a storage root. */ +class SharedAudioProvider : ContentProvider() { + companion object { + private const val FILES = "shared_audio_files" + + fun uriForFile(context: Context, file: File): Uri { + require(file.isAbsolute && file.isFile && file.canRead()) { "Audio file is not readable" } + val path = file.canonicalPath + val id = Base64.encodeToString( + MessageDigest.getInstance("SHA-256").digest(path.toByteArray(Charsets.UTF_8)), + Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING + ) + val files = context.getSharedPreferences(FILES, Context.MODE_PRIVATE) + if (files.getString(id, null) != path) { + check(files.edit().putString(id, path).commit()) { "Cannot register audio file for sharing" } + } + return Uri.Builder().scheme("content").authority("${context.packageName}.audio") + .appendPath(id).build() + } + } + + override fun onCreate(): Boolean = true + + private fun file(uri: Uri): File { + val context = requireNotNull(context) + if (uri.authority != "${context.packageName}.audio" || uri.pathSegments.size != 1) { + throw FileNotFoundException("Invalid audio URI") + } + val path = context.getSharedPreferences(FILES, Context.MODE_PRIVATE) + .getString(uri.lastPathSegment, null) ?: throw FileNotFoundException("Unknown audio URI") + val file = File(path) + if (file.canonicalPath != path || !file.isFile || !file.canRead()) { + throw FileNotFoundException("Audio file is no longer available") + } + return file + } + + override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor { + if (mode != "r") throw SecurityException("Audio sharing is read-only") + return ParcelFileDescriptor.open(file(uri), ParcelFileDescriptor.MODE_READ_ONLY) + } + + override fun getType(uri: Uri): String { + file(uri) + return "audio/*" + } + + override fun query(uri: Uri, projection: Array?, selection: String?, + selectionArgs: Array?, sortOrder: String?): Cursor { + val file = file(uri) + val columns = (projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)) + .filter { it == OpenableColumns.DISPLAY_NAME || it == OpenableColumns.SIZE }.toTypedArray() + return MatrixCursor(columns, 1).apply { + addRow(columns.map { if (it == OpenableColumns.DISPLAY_NAME) file.name else file.length() }) + } + } + + override fun insert(uri: Uri, values: ContentValues?): Uri = throw SecurityException("Read-only provider") + override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array?): Int = + throw SecurityException("Read-only provider") + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = + throw SecurityException("Read-only provider") +} diff --git a/lib/api/xmly_client.dart b/lib/api/xmly_client.dart index 6c8fa7f..f3093f5 100644 --- a/lib/api/xmly_client.dart +++ b/lib/api/xmly_client.dart @@ -880,6 +880,12 @@ class XmlyClient { definitive: true, ); } + if (origin == mobile && code == '924') + throw const XmlyException( + 'content_removed', + '该内容已下架', + definitive: true, + ); if (['5', '403', '726'].contains(code)) throw const XmlyException( 'permission_denied', @@ -920,6 +926,7 @@ class XmlyClient { 'login_required', 'login_expired', 'permission_denied', + 'content_removed', 'rate_limited', }.contains(error.code)), ); diff --git a/lib/api/xmly_comments.dart b/lib/api/xmly_comments.dart index 53c2d08..6fbf465 100644 --- a/lib/api/xmly_comments.dart +++ b/lib/api/xmly_comments.dart @@ -101,7 +101,16 @@ class AlbumReview { AlbumReviewReply? preview; if (replies is List && replies.isNotEmpty) { if (replies.first is! Map) throw XmlyComments._invalid; - preview = AlbumReviewReply.fromApi(xmlyMap(replies.first), commentId: id); + final reply = xmlyMap(replies.first); + // The reply-list endpoint's RootComment embeds only a reference, not a + // renderable preview. Full previews still require all reply fields. + if (reply.length == 2 && + reply.containsKey('replyId') && + reply['unFollowAnchor'] is bool) { + xmlyIdentifier('${reply['replyId'] ?? ''}'); + } else { + preview = AlbumReviewReply.fromApi(reply, commentId: id); + } } return AlbumReview( id: id, @@ -414,13 +423,34 @@ class XmlyComments { final pages = _count(data['maxPageId']); _count(data['totalCount']); final list = data['list']; + // A page past the current maxPageId is returned with the requested pageId + // and an empty list. Preserve those bounds rather than inventing a page. if (pageId != page || size < 1 || size > requestedSize || - (pages > 0 && page > pages) || list is! List || - list.length > size) { - throw _invalid; + list.length > size || + (pages > 0 && page > pages && list.isNotEmpty)) { + throw XmlyException( + 'invalid_comments', + _invalid.message, + diagnostics: { + 'requestedPage': page, + 'requestedSize': requestedSize, + for (final key in [ + 'pageId', + 'pageSize', + 'maxPageId', + 'totalCount', + 'list', + ]) + key: _diagnosticField( + data[key], + present: data.containsKey(key), + includeNumber: true, + ), + }, + ); } } diff --git a/lib/api/xmly_experience.dart b/lib/api/xmly_experience.dart index 2f6c132..3052c3a 100644 --- a/lib/api/xmly_experience.dart +++ b/lib/api/xmly_experience.dart @@ -828,7 +828,8 @@ class XmlyExperience { 'GET', XmlyClient.mobile, '/fsubscribe-web/subscribe/comprehensive/rank/$_stamp', - query: {'pageId': page, 'sign': 2, 'size': pageSize}, + // sign=2 refreshes the first page even when pageId is greater than one. + query: {'pageId': page, 'sign': page == 1 ? 2 : 1, 'size': pageSize}, ); if (response['data'] is! Map) throw _invalid; final data = response['data'] as Map; @@ -1086,6 +1087,7 @@ class XmlyExperience { if (!ids.add(track.id)) throw const XmlyException('repeated_page', '更新列表重复,请刷新后重试'); final timeline = _time(row['timeline']); + if (timeline <= 0) throw _invalid; if (cursor != null && timeline > cursor) throw _invalid; cursor = timeline; items.add( @@ -1095,13 +1097,14 @@ class XmlyExperience { ), ); } - final more = _more(data); + // The live feed can advertise more for a subscribed account yet return an + // empty page without a cursor. There is no next request until a refresh. + final more = _more(data) && items.isNotEmpty; // The live service may ignore timeline; do not present the repeated newest // page as older updates or claim that the complete feed was loaded. if (before != null && cursor != null && cursor >= before) { throw const XmlyException('repeated_page', '暂时无法读取更早的更新,已保留当前列表'); } - if (more && (cursor == null || cursor <= 0)) throw _invalid; return UpdatePage(items: items, hasMore: more, nextTimeline: cursor); } } diff --git a/lib/app.dart b/lib/app.dart index 41282c6..825dcb1 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -43,6 +43,7 @@ class _MyAppState extends State with WindowListener { late final _appearance = AppAppearance(widget.runtime.storage); final _navigator = GlobalKey(); final _messenger = GlobalKey(); + final _playerReturnTarget = GlobalKey(debugLabel: 'playerReturnTarget'); final _playerRoutes = _PlayerRouteObserver(); final _promptRoutes = LogUploadPromptObserver(); final _sentryRoutes = SentryNavigatorObserver(); @@ -182,7 +183,8 @@ class _MyAppState extends State with WindowListener { var updating = false; if (Platform.isWindows) { try { - updating = await const MethodChannel('teikengstudio.xmplus/update') + updating = + await const MethodChannel('teikengstudio.xmplus/update') .invokeMethod('isUpdateReady') ?? false; } catch (error, stack) { @@ -626,6 +628,80 @@ class _MyAppState extends State with WindowListener { super.dispose(); } + Widget _buildPlayerLayout(BuildContext context, Widget navigator) { + AppLog.instance.trace('lib/app.dart::_MyAppState._buildPlayerLayout'); + final android = Theme.of(context).platform == TargetPlatform.android; + final route = android ? _playerRoutes.playerTransition : null; + final blocked = _playerRoutes.current is PopupRoute || route != null; + final player = SafeArea( + top: false, + child: ExcludeFocus( + excluding: blocked, + child: ExcludeSemantics( + excluding: blocked, + child: AbsorbPointer( + absorbing: blocked, + child: PlayerPanel( + key: _playerReturnTarget, + runtime: widget.runtime, + navigatorKey: _navigator, + onExpand: !android + ? null + : () { + AppLog.instance.trace( + 'lib/app.dart::_MyAppState._buildPlayerLayout.closure#1', + ); + _navigator.currentState?.push( + PlayerPanelRoute( + runtime: widget.runtime, + returnTarget: _playerReturnTarget, + ), + ); + setState(() { + AppLog.instance.trace( + 'lib/app.dart::_MyAppState._buildPlayerLayout.closure#1.closure#1', + ); + }); + }, + ), + ), + ), + ), + ); + if (!android) { + return Column( + children: [ + Expanded(child: navigator), + if (_miniRoute == null && !_playerRoutes.playerExpanded) player, + ], + ); + } + return AnimatedBuilder( + animation: route?.animation ?? kAlwaysDismissedAnimation, + builder: (context, _) { + AppLog.instance.trace( + 'lib/app.dart::_MyAppState._buildPlayerLayout.closure#2', + ); + return CustomMultiChildLayout( + delegate: _PlayerLayoutDelegate(expanded: route != null), + children: [ + LayoutId(id: 'navigator', child: navigator), + if (_miniRoute == null) + LayoutId( + id: 'player', + child: Opacity( + opacity: route == null + ? 1 + : (1 - route.expansion / 0.2).clamp(0.0, 1.0), + child: player, + ), + ), + ], + ); + }, + ); + } + @override Widget build(BuildContext context) { AppLog.instance.trace("lib/app.dart::_MyAppState.build"); @@ -705,32 +781,7 @@ class _MyAppState extends State with WindowListener { !_exitPending && _closeDialog == null; }, - child: Column( - children: [ - Expanded(child: child!), - if (_miniRoute == null && - !_playerRoutes.playerExpanded) - SafeArea( - top: false, - child: ExcludeFocus( - excluding: - _playerRoutes.current is PopupRoute, - child: ExcludeSemantics( - excluding: - _playerRoutes.current is PopupRoute, - child: AbsorbPointer( - absorbing: - _playerRoutes.current is PopupRoute, - child: PlayerPanel( - runtime: widget.runtime, - navigatorKey: _navigator, - ), - ), - ), - ), - ), - ], - ), + child: _buildPlayerLayout(context, child!), ); }, ), @@ -775,10 +826,64 @@ class _MyAppState extends State with WindowListener { } } +// Lay out the real bar first so the route can measure its current bounds even +// during rotation/font changes. The navigator stays full-size until pop ends. +class _PlayerLayoutDelegate extends MultiChildLayoutDelegate { + _PlayerLayoutDelegate({required this.expanded}) { + AppLog.instance.trace('lib/app.dart::_PlayerLayoutDelegate.new'); + } + + final bool expanded; + + @override + void performLayout(Size size) { + AppLog.instance.trace('lib/app.dart::_PlayerLayoutDelegate.performLayout'); + var barHeight = 0.0; + if (hasChild('player')) { + barHeight = layoutChild( + 'player', + BoxConstraints( + minWidth: size.width, + maxWidth: size.width, + maxHeight: size.height, + ), + ).height; + positionChild('player', Offset(0, size.height - barHeight)); + } + layoutChild( + 'navigator', + BoxConstraints.tight( + Size(size.width, expanded ? size.height : size.height - barHeight), + ), + ); + positionChild('navigator', Offset.zero); + } + + @override + bool shouldRelayout(_PlayerLayoutDelegate oldDelegate) { + AppLog.instance.trace('lib/app.dart::_PlayerLayoutDelegate.shouldRelayout'); + return expanded != oldDelegate.expanded; + } +} + class _PlayerRouteObserver extends NavigatorObserver with ChangeNotifier { final _routes = >[]; Route? current; bool _disposed = false; + PlayerPanelRoute? _exitingPlayer; + + PlayerPanelRoute? get playerTransition { + AppLog.instance.trace( + 'lib/app.dart::_PlayerRouteObserver.playerTransition.get', + ); + if (_exitingPlayer case final route?) return route; + for (final route in _routes.reversed) { + if (route is PageRoute) { + return route is PlayerPanelRoute ? route : null; + } + } + return null; + } bool get playerExpanded { AppLog.instance.trace( @@ -817,6 +922,20 @@ class _PlayerRouteObserver extends NavigatorObserver with ChangeNotifier { void didPop(Route route, Route? previousRoute) { AppLog.instance.trace("lib/app.dart::_PlayerRouteObserver.didPop"); + if (route is PlayerPanelRoute) { + _exitingPlayer = route; + unawaited( + route.completed.then((_) { + AppLog.instance.trace( + 'lib/app.dart::_PlayerRouteObserver.didPop.closure#1', + ); + if (!_disposed && identical(_exitingPlayer, route)) { + _exitingPlayer = null; + notifyListeners(); + } + }), + ); + } _routes.remove(route); _changed(previousRoute); } diff --git a/lib/common/theme.dart b/lib/common/theme.dart index 91b92dd..11328e1 100644 --- a/lib/common/theme.dart +++ b/lib/common/theme.dart @@ -1,590 +1,609 @@ -// Adapted from PiliPlus lib/utils/theme_utils.dart::getThemeData and -// lib/common/style.dart, commit d9e9626f1a3f89cd9ca85e18f61aaba02634e12a. -// Original source: https://github.com/bggRGjQaUbCoE/PiliPlus (GNU GPL v3). -import 'dart:async'; - -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart' show PredictiveBackEvent; - -import '../services/app_log.dart'; -import '../storage/app_storage.dart'; - -class AppAppearance extends ChangeNotifier { - static const defaultSeedColor = 0xFF245C56; - - AppAppearance(this.storage) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.new"); - - _load(); - } - - final AppStorage storage; - ThemeMode _themeMode = ThemeMode.system; - Color _seedColor = const Color(defaultSeedColor); - double _textScale = 1; - bool _oledBlack = false; - final _pending = {}; - String? error; - - void reload() { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.reload"); - - _load(); - notifyListeners(); - } - - void _load() { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance._load"); - - final settings = storage.state['settings'] as Map; - final value = settings['appearance'] as Map? ?? const {}; - final mode = value['themeMode'] ?? 'system'; - _themeMode = ThemeMode.values.firstWhere((item) { - AppLog.instance.trace( - "lib/common/theme.dart::AppAppearance._load.closure#1", - ); - return item.name == mode; - }); - final color = value['seedColor'] ?? defaultSeedColor; - final scale = value['textScale'] ?? 1; - final oledBlack = value['oledBlack'] ?? false; - if (color is! int || - color < 0 || - color > 0xFFFFFFFF || - scale is! num || - !scale.isFinite || - scale < 0.8 || - scale > 1.5 || - oledBlack is! bool) { - throw const FormatException('外观设置无效,请恢复有效备份'); - } - _seedColor = Color(color); - _textScale = scale.toDouble(); - _oledBlack = oledBlack; - } - - Future _save(Map changes) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance._save"); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/common/theme.dart::AppAppearance._save.closure#1", - ); - - final request = Object(); - for (final key in changes.keys) { - _pending[key] = request; - } - try { - await storage.transaction((state) { - AppLog.instance.trace( - "lib/common/theme.dart::AppAppearance._save.closure#1.closure#1", - ); - - final settings = state['settings'] as Map; - final appearance = Map.from( - settings['appearance'] as Map? ?? const {}, - ); - settings['appearance'] = appearance..addAll(changes); - }); - _load(); - error = null; - } catch (failure, stack) { - if (!AppLog.instance.errorWasRecorded(failure)) { - AppLog.instance.write( - AppLogLevel.error, - 'appearance', - 'Saving appearance settings failed', - error: failure, - stackTrace: stack, - ); - } - AppLog.instance.requestUploadPrompt(); - error = '设置保存失败,原设置已保留'; - } finally { - for (final key in changes.keys) { - if (identical(_pending[key], request)) _pending.remove(key); - } - } - notifyListeners(); - }); - } - - ThemeMode get themeMode { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.themeMode.get"); - return _themeMode; - } - - Color get seedColor { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.seedColor.get"); - return _seedColor; - } - - double get textScale { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.textScale.get"); - return _textScale; - } - - bool get oledBlack { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.oledBlack.get"); - return _oledBlack; - } - - set themeMode(ThemeMode value) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.themeMode.set"); - - if (!_pending.containsKey('themeMode') && _themeMode == value) return; - unawaited(_save({'themeMode': value.name})); - } - - set seedColor(Color value) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.seedColor.set"); - - if (!_pending.containsKey('seedColor') && _seedColor == value) return; - unawaited(_save({'seedColor': value.toARGB32()})); - } - - set textScale(double value) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.textScale.set"); - - if (!value.isFinite || value < 0.8 || value > 1.5) { - throw RangeError.value( - value, - 'textScale', - 'Expected a finite value from 0.8 to 1.5', - ); - } - if (!_pending.containsKey('textScale') && _textScale == value) return; - unawaited(_save({'textScale': value})); - } - - set oledBlack(bool value) { - AppLog.instance.trace("lib/common/theme.dart::AppAppearance.oledBlack.set"); - - if (!_pending.containsKey('oledBlack') && _oledBlack == value) return; - unawaited(_save({'oledBlack': value})); - } -} - -class AppTextScaler extends TextScaler { - const AppTextScaler(this.systemScaler, this.appScale); - - final TextScaler systemScaler; - final double appScale; - - @override - double scale(double fontSize) { - AppLog.instance.trace("lib/common/theme.dart::AppTextScaler.scale"); - return systemScaler.scale(fontSize) * appScale; - } - - @override - double get textScaleFactor { - AppLog.instance.trace( - "lib/common/theme.dart::AppTextScaler.textScaleFactor.get", - ); - return scale(14) / 14; - } -} - -ThemeData getThemeData({ - required Color seedColor, - required Brightness brightness, - bool oledBlack = false, -}) { - AppLog.instance.trace("lib/common/theme.dart::getThemeData"); - - const fontFamily = 'HarmonyOS Sans SC'; - final dark = brightness == Brightness.dark; - final isOled = brightness == Brightness.dark && oledBlack; - var colorScheme = ColorScheme.fromSeed( - seedColor: seedColor, - brightness: brightness, - ); - if (isOled) { - colorScheme = colorScheme.copyWith( - surface: Colors.black, - surfaceDim: Colors.black, - surfaceBright: const Color(0xFF202020), - surfaceContainerLowest: Colors.black, - surfaceContainerLow: const Color(0xFF0A0A0A), - surfaceContainer: const Color(0xFF101010), - surfaceContainerHigh: const Color(0xFF181818), - surfaceContainerHighest: const Color(0xFF242424), - outline: const Color(0xFF96908E), - outlineVariant: const Color(0xFF45413F), - ); - } - final buttonStyle = ButtonStyle( - minimumSize: const WidgetStatePropertyAll(Size(48, 48)), - padding: const WidgetStatePropertyAll( - EdgeInsets.symmetric(horizontal: 20, vertical: 12), - ), - shape: WidgetStatePropertyAll( - RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), - ), - shadowColor: const WidgetStatePropertyAll(Colors.transparent), - animationDuration: const Duration(milliseconds: 160), - ); - final surfaceEdge = colorScheme.outlineVariant.withValues(alpha: .55); - final softShadow = colorScheme.shadow.withValues(alpha: dark ? .28 : .12); - return ThemeData( - useMaterial3: true, - colorScheme: colorScheme, - fontFamily: fontFamily, - scaffoldBackgroundColor: colorScheme.surface, - canvasColor: colorScheme.surface, - materialTapTargetSize: MaterialTapTargetSize.padded, - splashFactory: NoSplash.splashFactory, - hoverColor: colorScheme.onSurface.withValues(alpha: .04), - focusColor: colorScheme.primary.withValues(alpha: .1), - highlightColor: colorScheme.onSurface.withValues(alpha: .06), - textTheme: const TextTheme( - bodyLarge: TextStyle(fontSize: 15), - bodyMedium: TextStyle(fontSize: 14), - bodySmall: TextStyle(fontSize: 12), - titleLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w500), - titleMedium: TextStyle(fontSize: 15, fontWeight: FontWeight.w500), - titleSmall: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), - headlineLarge: TextStyle(fontSize: 26), - headlineMedium: TextStyle(fontSize: 24), - headlineSmall: TextStyle(fontSize: 20), - labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), - labelMedium: TextStyle(fontSize: 12, fontWeight: FontWeight.w500), - labelSmall: TextStyle(fontSize: 11, fontWeight: FontWeight.w500), - ), - pageTransitionsTheme: PageTransitionsTheme( - builders: { - ...const PageTransitionsTheme().builders, - TargetPlatform.android: const _FadePageTransitionsBuilder(), - TargetPlatform.windows: const _FadePageTransitionsBuilder(), - TargetPlatform.linux: const _FadePageTransitionsBuilder(), - }, - ), - appBarTheme: AppBarTheme( - elevation: 0, - titleSpacing: 16, - centerTitle: false, - scrolledUnderElevation: 0, - backgroundColor: colorScheme.surface, - surfaceTintColor: Colors.transparent, - titleTextStyle: TextStyle( - fontFamily: fontFamily, - fontSize: 16, - fontWeight: FontWeight.normal, - color: colorScheme.onSurface, - ), - ), - navigationBarTheme: NavigationBarThemeData( - backgroundColor: isOled ? Colors.black : colorScheme.surfaceContainerLow, - surfaceTintColor: Colors.transparent, - indicatorColor: colorScheme.primary.withValues(alpha: .1), - indicatorShape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - iconTheme: WidgetStateProperty.resolveWith((states) { - AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#1"); - - return IconThemeData( - color: states.contains(WidgetState.selected) - ? colorScheme.primary - : colorScheme.onSurfaceVariant, - ); - }), - ), - navigationRailTheme: NavigationRailThemeData( - backgroundColor: colorScheme.surface, - indicatorShape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - ), - ), - tabBarTheme: TabBarThemeData( - dividerHeight: 0, - indicatorSize: TabBarIndicatorSize.label, - indicatorAnimation: TabIndicatorAnimation.linear, - indicator: UnderlineTabIndicator( - borderSide: BorderSide(color: colorScheme.primary, width: 2), - borderRadius: BorderRadius.circular(2), - ), - labelColor: colorScheme.onSurface, - unselectedLabelColor: colorScheme.onSurfaceVariant, - labelStyle: const TextStyle(fontWeight: FontWeight.w600), - unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w500), - ), - scrollbarTheme: ScrollbarThemeData( - thumbVisibility: const WidgetStatePropertyAll(false), - trackVisibility: const WidgetStatePropertyAll(false), - thickness: WidgetStateProperty.resolveWith((states) { - AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#2"); - - return states.contains(WidgetState.hovered) || - states.contains(WidgetState.dragged) - ? 4.0 - : 2.5; - }), - thumbColor: WidgetStateProperty.resolveWith((states) { - AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#3"); - - final opacity = states.contains(WidgetState.dragged) - ? .48 - : states.contains(WidgetState.hovered) - ? .32 - : .18; - return colorScheme.onSurfaceVariant.withValues(alpha: opacity); - }), - radius: const Radius.circular(6), - crossAxisMargin: 3, - mainAxisMargin: 4, - minThumbLength: 28, - interactive: true, - ), - snackBarTheme: SnackBarThemeData( - elevation: 0, - actionTextColor: colorScheme.primary, - closeIconColor: colorScheme.secondary, - backgroundColor: colorScheme.secondaryContainer, - contentTextStyle: TextStyle( - fontFamily: fontFamily, - color: colorScheme.onSecondaryContainer, - ), - ), - popupMenuTheme: PopupMenuThemeData( - position: PopupMenuPosition.under, - surfaceTintColor: Colors.transparent, - elevation: 8, - shadowColor: softShadow, - color: colorScheme.surface, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(14), - side: BorderSide(color: surfaceEdge), - ), - ), - cardTheme: CardThemeData( - elevation: isOled ? 0 : .5, - margin: EdgeInsets.zero, - color: colorScheme.surfaceContainerLow, - shadowColor: softShadow, - surfaceTintColor: Colors.transparent, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(18), - side: BorderSide(color: surfaceEdge), - ), - ), - dialogTheme: DialogThemeData( - elevation: 12, - shadowColor: softShadow, - surfaceTintColor: Colors.transparent, - barrierColor: colorScheme.scrim.withValues(alpha: dark ? .32 : .2), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(18), - side: BorderSide(color: surfaceEdge), - ), - titleTextStyle: TextStyle( - fontFamily: fontFamily, - fontSize: 18, - fontWeight: FontWeight.normal, - color: colorScheme.onSurface, - ), - backgroundColor: colorScheme.surface, - constraints: const BoxConstraints(minWidth: 280, maxWidth: 420), - ), - bottomSheetTheme: BottomSheetThemeData( - backgroundColor: colorScheme.surface, - surfaceTintColor: Colors.transparent, - elevation: 0, - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(top: Radius.circular(18)), - ), - ), - tooltipTheme: TooltipThemeData( - waitDuration: const Duration(milliseconds: 700), - exitDuration: const Duration(milliseconds: 100), - showDuration: const Duration(seconds: 2), - preferBelow: false, - verticalOffset: 20, - constraints: const BoxConstraints(minHeight: 24, maxWidth: 240), - padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), - margin: const EdgeInsets.symmetric(horizontal: 12), - textStyle: TextStyle( - fontFamily: fontFamily, - fontSize: 12, - height: 1.2, - color: colorScheme.onInverseSurface, - ), - decoration: BoxDecoration( - color: colorScheme.inverseSurface.withValues(alpha: .94), - borderRadius: BorderRadius.circular(6), - boxShadow: [ - BoxShadow( - color: softShadow, - blurRadius: 12, - offset: const Offset(0, 2), - ), - ], - ), - ), - expansionTileTheme: const ExpansionTileThemeData( - shape: Border(), - collapsedShape: Border(), - ), - listTileTheme: const ListTileThemeData( - controlAffinity: ListTileControlAffinity.leading, - minTileHeight: 48, - minVerticalPadding: 10, - horizontalTitleGap: 12, - ), - inputDecorationTheme: InputDecorationTheme( - filled: true, - fillColor: colorScheme.surfaceContainerLow, - contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(14), - borderSide: BorderSide(color: colorScheme.outlineVariant), - ), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(14), - borderSide: BorderSide(color: colorScheme.outlineVariant), - ), - focusedBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular(14), - borderSide: BorderSide(color: colorScheme.primary, width: 2), - ), - ), - filledButtonTheme: FilledButtonThemeData(style: buttonStyle), - outlinedButtonTheme: OutlinedButtonThemeData(style: buttonStyle), - textButtonTheme: TextButtonThemeData(style: buttonStyle), - elevatedButtonTheme: ElevatedButtonThemeData( - style: buttonStyle.copyWith(elevation: const WidgetStatePropertyAll(0)), - ), - ); -} - -class _FadePageTransitionsBuilder extends PageTransitionsBuilder { - const _FadePageTransitionsBuilder(); - - @override - Duration get transitionDuration { - AppLog.instance.trace( - "lib/common/theme.dart::_FadePageTransitionsBuilder.transitionDuration.get", - ); - return const Duration(milliseconds: 180); - } - - @override - Widget buildTransitions( - PageRoute route, - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) { - AppLog.instance.trace( - "lib/common/theme.dart::_FadePageTransitionsBuilder.buildTransitions", - ); - if (Theme.of(context).platform != TargetPlatform.android) { - if (MediaQuery.disableAnimationsOf(context)) return child; - return FadeTransition( - opacity: animation.drive(CurveTween(curve: Curves.easeOutCubic)), - child: child, - ); - } - return _PredictiveBackFadeTransition( - route: route, - animation: animation, - child: child, - ); - } -} - -class _PredictiveBackFadeTransition extends StatefulWidget { - const _PredictiveBackFadeTransition({ - required this.route, - required this.animation, - required this.child, - }); - - final PageRoute route; - final Animation animation; - final Widget child; - - @override - State<_PredictiveBackFadeTransition> createState() { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransition.createState", - ); - return _PredictiveBackFadeTransitionState(); - } -} - -class _PredictiveBackFadeTransitionState - extends State<_PredictiveBackFadeTransition> - with WidgetsBindingObserver { - @override - void initState() { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.initState", - ); - - super.initState(); - WidgetsBinding.instance.addObserver(this); - } - - @override - bool handleStartBackGesture(PredictiveBackEvent backEvent) { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleStartBackGesture", - ); - - if (backEvent.isButtonEvent || - !widget.route.isCurrent || - !widget.route.popGestureEnabled) { - return false; - } - widget.route.handleStartBackGesture(progress: 1 - backEvent.progress); - return true; - } - - @override - void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleUpdateBackGestureProgress", - ); - widget.route.handleUpdateBackGestureProgress( - progress: 1 - backEvent.progress, - ); - } - - @override - void handleCancelBackGesture() { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleCancelBackGesture", - ); - widget.route.handleCancelBackGesture(); - } - - @override - void handleCommitBackGesture() { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleCommitBackGesture", - ); - widget.route.handleCommitBackGesture(); - } - - @override - void dispose() { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.dispose", - ); - - WidgetsBinding.instance.removeObserver(this); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - "lib/common/theme.dart::_PredictiveBackFadeTransitionState.build", - ); - if (MediaQuery.disableAnimationsOf(context)) return widget.child; - return FadeTransition(opacity: widget.animation, child: widget.child); - } -} +// Adapted from PiliPlus lib/utils/theme_utils.dart::getThemeData and +// lib/common/style.dart, commit d9e9626f1a3f89cd9ca85e18f61aaba02634e12a. +// Original source: https://github.com/bggRGjQaUbCoE/PiliPlus (GNU GPL v3). +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart' show PredictiveBackEvent; + +import '../services/app_log.dart'; +import '../storage/app_storage.dart'; + +class AppAppearance extends ChangeNotifier { + static const defaultSeedColor = 0xFF245C56; + + AppAppearance(this.storage) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.new"); + + _load(); + } + + final AppStorage storage; + ThemeMode _themeMode = ThemeMode.system; + Color _seedColor = const Color(defaultSeedColor); + double _textScale = 1; + bool _oledBlack = false; + final _pending = {}; + String? error; + + void reload() { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.reload"); + + _load(); + notifyListeners(); + } + + void _load() { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance._load"); + + final settings = storage.state['settings'] as Map; + final value = settings['appearance'] as Map? ?? const {}; + final mode = value['themeMode'] ?? 'system'; + _themeMode = ThemeMode.values.firstWhere((item) { + AppLog.instance.trace( + "lib/common/theme.dart::AppAppearance._load.closure#1", + ); + return item.name == mode; + }); + final color = value['seedColor'] ?? defaultSeedColor; + final scale = value['textScale'] ?? 1; + final oledBlack = value['oledBlack'] ?? false; + if (color is! int || + color < 0 || + color > 0xFFFFFFFF || + scale is! num || + !scale.isFinite || + scale < 0.8 || + scale > 1.5 || + oledBlack is! bool) { + throw const FormatException('外观设置无效,请恢复有效备份'); + } + _seedColor = Color(color); + _textScale = scale.toDouble(); + _oledBlack = oledBlack; + } + + Future _save(Map changes) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance._save"); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/common/theme.dart::AppAppearance._save.closure#1", + ); + + final request = Object(); + for (final key in changes.keys) { + _pending[key] = request; + } + try { + await storage.transaction((state) { + AppLog.instance.trace( + "lib/common/theme.dart::AppAppearance._save.closure#1.closure#1", + ); + + final settings = state['settings'] as Map; + final appearance = Map.from( + settings['appearance'] as Map? ?? const {}, + ); + settings['appearance'] = appearance..addAll(changes); + }); + _load(); + error = null; + } catch (failure, stack) { + if (!AppLog.instance.errorWasRecorded(failure)) { + AppLog.instance.write( + AppLogLevel.error, + 'appearance', + 'Saving appearance settings failed', + error: failure, + stackTrace: stack, + ); + } + AppLog.instance.requestUploadPrompt(); + error = '设置保存失败,原设置已保留'; + } finally { + for (final key in changes.keys) { + if (identical(_pending[key], request)) _pending.remove(key); + } + } + notifyListeners(); + }); + } + + ThemeMode get themeMode { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.themeMode.get"); + return _themeMode; + } + + Color get seedColor { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.seedColor.get"); + return _seedColor; + } + + double get textScale { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.textScale.get"); + return _textScale; + } + + bool get oledBlack { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.oledBlack.get"); + return _oledBlack; + } + + set themeMode(ThemeMode value) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.themeMode.set"); + + if (!_pending.containsKey('themeMode') && _themeMode == value) return; + unawaited(_save({'themeMode': value.name})); + } + + set seedColor(Color value) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.seedColor.set"); + + if (!_pending.containsKey('seedColor') && _seedColor == value) return; + unawaited(_save({'seedColor': value.toARGB32()})); + } + + set textScale(double value) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.textScale.set"); + + if (!value.isFinite || value < 0.8 || value > 1.5) { + throw RangeError.value( + value, + 'textScale', + 'Expected a finite value from 0.8 to 1.5', + ); + } + if (!_pending.containsKey('textScale') && _textScale == value) return; + unawaited(_save({'textScale': value})); + } + + set oledBlack(bool value) { + AppLog.instance.trace("lib/common/theme.dart::AppAppearance.oledBlack.set"); + + if (!_pending.containsKey('oledBlack') && _oledBlack == value) return; + unawaited(_save({'oledBlack': value})); + } +} + +class AppTextScaler extends TextScaler { + const AppTextScaler(this.systemScaler, this.appScale); + + final TextScaler systemScaler; + final double appScale; + + @override + double scale(double fontSize) { + AppLog.instance.trace("lib/common/theme.dart::AppTextScaler.scale"); + return systemScaler.scale(fontSize) * appScale; + } + + @override + double get textScaleFactor { + AppLog.instance.trace( + "lib/common/theme.dart::AppTextScaler.textScaleFactor.get", + ); + return scale(14) / 14; + } +} + +ThemeData getThemeData({ + required Color seedColor, + required Brightness brightness, + bool oledBlack = false, +}) { + AppLog.instance.trace("lib/common/theme.dart::getThemeData"); + + const fontFamily = 'HarmonyOS Sans SC'; + final dark = brightness == Brightness.dark; + final isOled = brightness == Brightness.dark && oledBlack; + var colorScheme = ColorScheme.fromSeed( + seedColor: seedColor, + brightness: brightness, + ); + if (isOled) { + colorScheme = colorScheme.copyWith( + surface: Colors.black, + surfaceDim: Colors.black, + surfaceBright: const Color(0xFF202020), + surfaceContainerLowest: Colors.black, + surfaceContainerLow: const Color(0xFF0A0A0A), + surfaceContainer: const Color(0xFF101010), + surfaceContainerHigh: const Color(0xFF181818), + surfaceContainerHighest: const Color(0xFF242424), + outline: const Color(0xFF96908E), + outlineVariant: const Color(0xFF45413F), + ); + } + final buttonStyle = ButtonStyle( + minimumSize: const WidgetStatePropertyAll(Size(48, 48)), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 20, vertical: 12), + ), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), + ), + shadowColor: const WidgetStatePropertyAll(Colors.transparent), + animationDuration: const Duration(milliseconds: 160), + ); + final surfaceEdge = colorScheme.outlineVariant.withValues(alpha: .55); + final softShadow = colorScheme.shadow.withValues(alpha: dark ? .28 : .12); + return ThemeData( + useMaterial3: true, + colorScheme: colorScheme, + fontFamily: fontFamily, + scaffoldBackgroundColor: colorScheme.surface, + canvasColor: colorScheme.surface, + materialTapTargetSize: MaterialTapTargetSize.padded, + splashFactory: NoSplash.splashFactory, + hoverColor: colorScheme.onSurface.withValues(alpha: .04), + focusColor: colorScheme.primary.withValues(alpha: .1), + highlightColor: colorScheme.onSurface.withValues(alpha: .06), + textTheme: const TextTheme( + bodyLarge: TextStyle(fontSize: 15), + bodyMedium: TextStyle(fontSize: 14), + bodySmall: TextStyle(fontSize: 12), + titleLarge: TextStyle(fontSize: 18, fontWeight: FontWeight.w500), + titleMedium: TextStyle(fontSize: 15, fontWeight: FontWeight.w500), + titleSmall: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), + headlineLarge: TextStyle(fontSize: 26), + headlineMedium: TextStyle(fontSize: 24), + headlineSmall: TextStyle(fontSize: 20), + labelLarge: TextStyle(fontSize: 14, fontWeight: FontWeight.w500), + labelMedium: TextStyle(fontSize: 12, fontWeight: FontWeight.w500), + labelSmall: TextStyle(fontSize: 11, fontWeight: FontWeight.w500), + ), + pageTransitionsTheme: PageTransitionsTheme( + builders: { + ...const PageTransitionsTheme().builders, + TargetPlatform.android: const _FadePageTransitionsBuilder(), + TargetPlatform.windows: const _FadePageTransitionsBuilder(), + TargetPlatform.linux: const _FadePageTransitionsBuilder(), + }, + ), + appBarTheme: AppBarTheme( + elevation: 0, + titleSpacing: 16, + centerTitle: false, + scrolledUnderElevation: 0, + backgroundColor: colorScheme.surface, + surfaceTintColor: Colors.transparent, + titleTextStyle: TextStyle( + fontFamily: fontFamily, + fontSize: 16, + fontWeight: FontWeight.normal, + color: colorScheme.onSurface, + ), + ), + navigationBarTheme: NavigationBarThemeData( + backgroundColor: isOled ? Colors.black : colorScheme.surfaceContainerLow, + surfaceTintColor: Colors.transparent, + indicatorColor: colorScheme.primary.withValues(alpha: .1), + indicatorShape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + iconTheme: WidgetStateProperty.resolveWith((states) { + AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#1"); + + return IconThemeData( + color: states.contains(WidgetState.selected) + ? colorScheme.primary + : colorScheme.onSurfaceVariant, + ); + }), + ), + navigationRailTheme: NavigationRailThemeData( + backgroundColor: colorScheme.surface, + indicatorShape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + tabBarTheme: TabBarThemeData( + dividerHeight: 0, + indicatorSize: TabBarIndicatorSize.label, + indicatorAnimation: TabIndicatorAnimation.linear, + indicator: UnderlineTabIndicator( + borderSide: BorderSide(color: colorScheme.primary, width: 2), + borderRadius: BorderRadius.circular(2), + ), + labelColor: colorScheme.onSurface, + unselectedLabelColor: colorScheme.onSurfaceVariant, + labelStyle: const TextStyle(fontWeight: FontWeight.w600), + unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.w500), + ), + scrollbarTheme: ScrollbarThemeData( + thumbVisibility: const WidgetStatePropertyAll(false), + trackVisibility: const WidgetStatePropertyAll(false), + thickness: WidgetStateProperty.resolveWith((states) { + AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#2"); + + return states.contains(WidgetState.hovered) || + states.contains(WidgetState.dragged) + ? 4.0 + : 2.5; + }), + thumbColor: WidgetStateProperty.resolveWith((states) { + AppLog.instance.trace("lib/common/theme.dart::getThemeData.closure#3"); + + final opacity = states.contains(WidgetState.dragged) + ? .48 + : states.contains(WidgetState.hovered) + ? .32 + : .18; + return colorScheme.onSurfaceVariant.withValues(alpha: opacity); + }), + radius: const Radius.circular(6), + crossAxisMargin: 3, + mainAxisMargin: 4, + minThumbLength: 28, + interactive: true, + ), + snackBarTheme: SnackBarThemeData( + elevation: 0, + actionTextColor: colorScheme.primary, + closeIconColor: colorScheme.secondary, + backgroundColor: colorScheme.secondaryContainer, + contentTextStyle: TextStyle( + fontFamily: fontFamily, + color: colorScheme.onSecondaryContainer, + ), + ), + popupMenuTheme: PopupMenuThemeData( + position: PopupMenuPosition.under, + surfaceTintColor: Colors.transparent, + elevation: 8, + shadowColor: softShadow, + color: colorScheme.surface, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: BorderSide(color: surfaceEdge), + ), + ), + cardTheme: CardThemeData( + elevation: isOled ? 0 : .5, + margin: EdgeInsets.zero, + color: colorScheme.surfaceContainerLow, + shadowColor: softShadow, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(18), + side: BorderSide(color: surfaceEdge), + ), + ), + dialogTheme: DialogThemeData( + elevation: 12, + shadowColor: softShadow, + surfaceTintColor: Colors.transparent, + barrierColor: colorScheme.scrim.withValues(alpha: dark ? .32 : .2), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(18), + side: BorderSide(color: surfaceEdge), + ), + titleTextStyle: TextStyle( + fontFamily: fontFamily, + fontSize: 18, + fontWeight: FontWeight.normal, + color: colorScheme.onSurface, + ), + backgroundColor: colorScheme.surface, + constraints: const BoxConstraints(minWidth: 280, maxWidth: 420), + ), + bottomSheetTheme: BottomSheetThemeData( + backgroundColor: colorScheme.surface, + surfaceTintColor: Colors.transparent, + elevation: 0, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(18)), + ), + ), + tooltipTheme: TooltipThemeData( + waitDuration: const Duration(milliseconds: 700), + exitDuration: const Duration(milliseconds: 100), + showDuration: const Duration(seconds: 2), + preferBelow: false, + verticalOffset: 20, + constraints: const BoxConstraints(minHeight: 24, maxWidth: 240), + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5), + margin: const EdgeInsets.symmetric(horizontal: 12), + textStyle: TextStyle( + fontFamily: fontFamily, + fontSize: 12, + height: 1.2, + color: colorScheme.onInverseSurface, + ), + decoration: BoxDecoration( + color: colorScheme.inverseSurface.withValues(alpha: .94), + borderRadius: BorderRadius.circular(6), + boxShadow: [ + BoxShadow( + color: softShadow, + blurRadius: 12, + offset: const Offset(0, 2), + ), + ], + ), + ), + expansionTileTheme: const ExpansionTileThemeData( + shape: Border(), + collapsedShape: Border(), + ), + listTileTheme: const ListTileThemeData( + controlAffinity: ListTileControlAffinity.leading, + minTileHeight: 48, + minVerticalPadding: 10, + horizontalTitleGap: 12, + ), + inputDecorationTheme: InputDecorationTheme( + filled: true, + fillColor: colorScheme.surfaceContainerLow, + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide(color: colorScheme.outlineVariant), + ), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide(color: colorScheme.outlineVariant), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(14), + borderSide: BorderSide(color: colorScheme.primary, width: 2), + ), + ), + filledButtonTheme: FilledButtonThemeData(style: buttonStyle), + outlinedButtonTheme: OutlinedButtonThemeData(style: buttonStyle), + textButtonTheme: TextButtonThemeData(style: buttonStyle), + elevatedButtonTheme: ElevatedButtonThemeData( + style: buttonStyle.copyWith(elevation: const WidgetStatePropertyAll(0)), + ), + ); +} + +class _FadePageTransitionsBuilder extends PageTransitionsBuilder { + const _FadePageTransitionsBuilder(); + + @override + Duration get transitionDuration { + AppLog.instance.trace( + "lib/common/theme.dart::_FadePageTransitionsBuilder.transitionDuration.get", + ); + return const Duration(milliseconds: 180); + } + + @override + Widget buildTransitions( + PageRoute route, + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + AppLog.instance.trace( + "lib/common/theme.dart::_FadePageTransitionsBuilder.buildTransitions", + ); + if (Theme.of(context).platform != TargetPlatform.android) { + if (MediaQuery.disableAnimationsOf(context)) return child; + return FadeTransition( + opacity: animation.drive(CurveTween(curve: Curves.easeOutCubic)), + child: child, + ); + } + return _PredictiveBackFadeTransition( + route: route, + animation: animation, + child: child, + ); + } +} + +class _PredictiveBackFadeTransition extends StatefulWidget { + const _PredictiveBackFadeTransition({ + required this.route, + required this.animation, + required this.child, + }); + + final PageRoute route; + final Animation animation; + final Widget child; + + @override + State<_PredictiveBackFadeTransition> createState() { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransition.createState", + ); + return _PredictiveBackFadeTransitionState(); + } +} + +class _PredictiveBackFadeTransitionState + extends State<_PredictiveBackFadeTransition> + with WidgetsBindingObserver { + Animation? _committedOpacity; + + @override + void initState() { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.initState", + ); + + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + bool handleStartBackGesture(PredictiveBackEvent backEvent) { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleStartBackGesture", + ); + + if (backEvent.isButtonEvent || + !widget.route.isCurrent || + !widget.route.popGestureEnabled) { + return false; + } + _committedOpacity = null; + widget.route.handleStartBackGesture(progress: 1 - backEvent.progress); + return true; + } + + @override + void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleUpdateBackGestureProgress", + ); + widget.route.handleUpdateBackGestureProgress( + progress: 1 - backEvent.progress, + ); + } + + @override + void handleCancelBackGesture() { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleCancelBackGesture", + ); + widget.route.handleCancelBackGesture(); + } + + @override + void handleCommitBackGesture() { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleCommitBackGesture", + ); + final opacity = (_committedOpacity ?? widget.animation).value; + widget.route.handleCommitBackGesture(); + final start = widget.animation.value; + if (!mounted || start == 0 || start == opacity) return; + setState(() { + AppLog.instance.trace( + 'lib/common/theme.dart::_PredictiveBackFadeTransitionState.handleCommitBackGesture.closure#1', + ); + // Keep the visible opacity when Flutter rebases its commit animation. + _committedOpacity = Tween( + begin: 0, + end: opacity / start, + ).animate(widget.animation); + }); + } + + @override + void dispose() { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.dispose", + ); + + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + "lib/common/theme.dart::_PredictiveBackFadeTransitionState.build", + ); + if (MediaQuery.disableAnimationsOf(context)) return widget.child; + return FadeTransition( + opacity: _committedOpacity ?? widget.animation, + child: widget.child, + ); + } +} diff --git a/lib/pages/album_reviews_page.dart b/lib/pages/album_reviews_page.dart index 3c9b4fb..6ffb3fe 100644 --- a/lib/pages/album_reviews_page.dart +++ b/lib/pages/album_reviews_page.dart @@ -133,6 +133,7 @@ class _AlbumReviewsPageState extends State { _cancelled?.complete(); final cancelled = _cancelled = Completer(); final client = _client, albumId = widget.albumId; + final newest = _newest; setState(() { AppLog.instance.trace( 'lib/pages/album_reviews_page.dart::_AlbumReviewsPageState._load.closure#1', @@ -143,12 +144,32 @@ class _AlbumReviewsPageState extends State { }); try { final result = await client.withReadPolicy( - () { + () async { AppLog.instance.trace( 'lib/pages/album_reviews_page.dart::_AlbumReviewsPageState._load.closure#2', ); - return XmlyComments(client) - .loadAlbumReviews(albumId, page: page, newest: _newest); + final comments = XmlyComments(client); + var result = await comments.loadAlbumReviews( + albumId, + page: page, + newest: newest, + ); + if (result.comments.isEmpty && + result.maxPageId > 0 && + result.page > result.maxPageId) { + result = await comments.loadAlbumReviews( + albumId, + page: result.maxPageId, + newest: newest, + ); + if (result.maxPageId > 0 && result.page > result.maxPageId) { + throw const XmlyException( + 'review_page_changed', + '评论页数已变化,请刷新后重试', + ); + } + } + return result; }, rateLimitRetries: 4, cancelled: cancelled.future, @@ -730,12 +751,32 @@ class _ReviewRepliesState extends State<_ReviewReplies> { }); try { final result = await client.withReadPolicy( - () { + () async { AppLog.instance.trace( 'lib/pages/album_reviews_page.dart::_ReviewRepliesState._load.closure#2', ); - return XmlyComments(client) - .loadAlbumReviewReplies(albumId, rootId, page: page); + final comments = XmlyComments(client); + var result = await comments.loadAlbumReviewReplies( + albumId, + rootId, + page: page, + ); + if (result.replies.isEmpty && + result.maxPageId > 0 && + result.page > result.maxPageId) { + result = await comments.loadAlbumReviewReplies( + albumId, + rootId, + page: result.maxPageId, + ); + if (result.maxPageId > 0 && result.page > result.maxPageId) { + throw const XmlyException( + 'review_page_changed', + '回复页数已变化,请刷新后重试', + ); + } + } + return result; }, rateLimitRetries: 4, cancelled: cancelled.future, diff --git a/lib/pages/download_page.dart b/lib/pages/download_page.dart index 2c00a65..ab61e07 100644 --- a/lib/pages/download_page.dart +++ b/lib/pages/download_page.dart @@ -1,3155 +1,3240 @@ -import 'dart:async'; -import 'dart:io'; -import 'dart:math' as math; - -import 'package:flutter/material.dart'; -import 'package:path/path.dart' as p; -import 'package:file_picker/file_picker.dart'; - -import '../common/widgets/app_scrollbar.dart'; -import '../common/widgets/adaptive_text.dart'; -import '../services/app_runtime.dart'; -import '../services/app_log.dart'; -import '../services/account_service.dart'; -import '../storage/app_storage.dart'; -import '../services/download_service.dart'; -import '../models/xmly_models.dart'; -import '../services/auto_download_service.dart'; -import '../services/android_platform.dart'; -import '../services/file_paths.dart'; -import 'catalogue_page.dart'; - -void _recordDownloadPageError(Object error, StackTrace stack) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_recordDownloadPageError", - ); - - if (error is DownloadStopped || - (error is StorageException && - const {'too_large', 'secret_in_state'}.contains(error.code)) || - (error is AccountException && - const { - 'credential_missing', - 'missing', - 'paused', - 'closed', - 'not_loaded', - 'credential_mismatch', - 'archive_invalid', - 'quota_invalid', - 'unsettled', - }.contains(error.code)) || - (error is XmlyException && - const { - 'invalid_id', - 'invalid_credentials', - 'invalid_quality', - 'invalid_retry', - 'invalid_settings', - 'invalid_duration', - 'invalid_space', - 'invalid_conflict', - 'media_format', - 'media_bitrate', - 'media_settings', - 'media_tags', - 'receipt_required', - 'cache_paused', - 'cache_closed', - 'login_required', - 'login_expired', - 'auth_required', - 'missing_account', - 'confirmation_required', - 'confirmation_changed', - 'insufficient_quota', - 'usage_uncertain', - 'original_account_required', - 'task_busy', - 'task_missing', - 'batch_invalid', - 'batch_too_large', - 'catalogue_limit', - 'download_changed', - 'shared_audio', - 'audio_changed', - 'closed', - 'client_closed', - 'request_cancelled', - }.contains(error.code)) || - AppLog.instance.errorWasRecorded(error)) - return; - AppLog.instance.write( - AppLogLevel.error, - 'download', - 'Download page action failed', - error: error, - stackTrace: stack, - promptUser: true, - ); -} - -Future<({String identity, bool polling})?> _chooseDownloadAccount( - BuildContext context, - AppRuntime runtime, -) async { - AppLog.instance.trace("lib/pages/download_page.dart::_chooseDownloadAccount"); - - final primary = runtime.accounts.primaryAccountId ?? 'anonymous'; - final accountIds = runtime.accounts.accountIds; - var polling = - ((runtime.storage.state['settings'] as Map)['download'] - as Map?)?['polling'] != - false; - if (accountIds.isEmpty) return (identity: 'anonymous', polling: false); - final selected = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1", - ); - return StatefulBuilder( - builder: (context, setState) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1", - ); - return SimpleDialog( - title: const Text('下载账号'), - children: [ - SwitchListTile( - title: const Text('轮询'), - subtitle: const Text('请求失败时尝试下一个账号;扣时结果不明时停止'), - value: polling, - onChanged: (value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#1", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#1.closure#1", - ); - polling = value; - }); - }, - ), - for (final id in accountIds) - SimpleDialogOption( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#2", - ); - Navigator.pop(context, id); - }, - child: Text( - '账号 ${(runtime.storage.state['accounts'] as Map)[id]['uid']}' - '${id == primary ? ' · 主账号' : ''}', - ), - ), - SimpleDialogOption( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#3", - ); - Navigator.pop(context, 'anonymous'); - }, - child: const Text('不登录(免费内容)'), - ), - ], - ); - }, - ); - }, - ); - if (selected == null) return null; - await runtime.storage.transaction((state) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#2", - ); - - final settings = state['settings'] as Map; - final download = settings.putIfAbsent('download', () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_chooseDownloadAccount.closure#2.closure#1", - ); - return {}; - }) as Map; - download['polling'] = polling; - }); - return (identity: selected, polling: selected != 'anonymous' && polling); -} - -Future requestDownloads( - BuildContext context, - AppRuntime runtime, - List tracks, { - String? accountIdentity, -}) async { - AppLog.instance.trace("lib/pages/download_page.dart::requestDownloads"); - - final account = accountIdentity == null - ? await _chooseDownloadAccount(context, runtime) - : (identity: accountIdentity, polling: false); - if (account == null || !context.mounted) return; - final batch = await runtime.prepareDownloads( - tracks, - accountIdentity: account.identity, - polling: account.polling, - previewBilling: false, - ); - if (!context.mounted) return; - if (batch.items.isEmpty) { - ScaffoldMessenger.of(context) - .showSnackBar(const SnackBar(content: Text('所选声音已在下载列表中'))); - return; - } - await runtime.downloads.enqueue(batch, confirmed: true); -} - -Future requestAlbumDownloads( - BuildContext context, - AppRuntime runtime, - String albumId, { - String? accountIdentity, -}) async { - AppLog.instance.trace("lib/pages/download_page.dart::requestAlbumDownloads"); - - final account = accountIdentity == null - ? await _chooseDownloadAccount(context, runtime) - : (identity: accountIdentity, polling: false); - if (account == null || !context.mounted) return; - final batch = await runtime.prepareAlbumDownloads( - albumId, - accountIdentity: account.identity, - polling: account.polling, - ); - if (!context.mounted) return; - await runtime.downloads.enqueue(batch, confirmed: true); -} - -Future deleteDownloadedAudio( - BuildContext context, - AppRuntime runtime, - DownloadTask task, -) async { - AppLog.instance.trace("lib/pages/download_page.dart::deleteDownloadedAudio"); - - final path = task.finalPath; - if (path == null) return false; - final confirmed = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1", - ); - return AlertDialog( - scrollable: true, - title: const Text( - '删除音频文件?', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SelectableText(path), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1.closure#1", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1.closure#2", - ); - Navigator.pop(context, true); - }, - child: const Text('删除文件'), - ), - ], - ); - }, - ); - if (confirmed != true) return false; - await _deleteAudioGroup(runtime, [task]); - return true; -} - -String _audioPathKey(String path) { - AppLog.instance.trace("lib/pages/download_page.dart::_audioPathKey"); - return Platform.isWindows - ? absoluteFilePath(path).toLowerCase() - : absoluteFilePath(path); -} - -Future _deleteAudioGroup( - AppRuntime runtime, - List tasks, { - void Function(int bytes)? onDeleted, -}) { - AppLog.instance.trace("lib/pages/download_page.dart::_deleteAudioGroup"); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_deleteAudioGroup.closure#1", - ); - - final path = tasks.first.finalPath!; - final key = _audioPathKey(path); - final ids = tasks.map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.closure#1", - ); - return task.id; - }).toSet(); - void validate() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.validate", - ); - - for (final expected in tasks) { - final current = runtime.downloads.task(expected.id); - if (current.state != DownloadState.completed || - current.finalPath != expected.finalPath || - current.accountIdentity != expected.accountIdentity || - current.track.id != expected.track.id) { - throw const XmlyException('download_changed', '下载记录已变化,请重新选择后删除'); - } - } - if (runtime.downloads.tasks.any((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.validate.closure#1", - ); - return task.state == DownloadState.completed && - task.finalPath != null && - _audioPathKey(task.finalPath!) == key && - !ids.contains(task.id); - })) { - throw const XmlyException('shared_audio', '其他下载记录也引用此文件,请一并选择后删除'); - } - } - - validate(); - for (final task in tasks) { - await runtime.player.stopTaskReference(task.id); - } - validate(); - final type = await FileSystemEntity.type(path, followLinks: false); - if (type == FileSystemEntityType.notFound) { - for (final task in tasks) { - await runtime.downloads.markAudioMissing( - task.id, - expectedPath: task.finalPath!, - ); - } - return; - } - if (type != FileSystemEntityType.file) { - throw const XmlyException('audio_changed', '音频路径已不是普通文件,请检查下载目录'); - } - final file = File(path); - final bytes = await file.length(); - validate(); - await file.delete(); - onDeleted?.call(bytes); - for (final task in tasks) { - try { - await runtime.downloads.markAudioDeleted( - task.id, - expectedPath: task.finalPath, - ); - } catch (error, stack) { - if (!AppLog.instance.errorWasRecorded(error)) { - AppLog.instance.write( - AppLogLevel.error, - 'download', - 'Updating deleted audio record failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - } - const replacement = XmlyException( - 'audio_record_update_failed', - '音频文件已删除,但记录更新未完成,请刷新后检查', - ); - AppLog.instance.linkError(replacement, error); - throw replacement; - } - } - }); -} - -Future setAlbumAutoDownload( - BuildContext context, - AutoDownloadService service, - String identity, - String albumId, - String title, -) async { - AppLog.instance.trace("lib/pages/download_page.dart::setAlbumAutoDownload"); - - if (service.enabled(identity, albumId)) { - await service.setEnabled(identity, albumId, confirmed: false); - return; - } - final account = (service.storage.state['accounts'] as Map)[identity]; - final label = account is Map && account['uid'] is String - ? account['uid'] as String - : identity; - final accepted = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1", - ); - return AlertDialog( - scrollable: true, - title: const Text( - '自动下载新声音', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SingleChildScrollView( - child: Text( - '${title.isEmpty ? "此专辑" : title}\n账号 $label\n\n' - '开启后,启动应用或打开专辑时检查更新,只下载开启后新增的声音,不补下已有集数。\n\n' - '始终使用此账号及正常下载规则。奖励内容会逐集预扣整首听时,未来新增声音不再逐次询问;' - '失败或取消不自动退回。余额不足、登录失效或扣时结果未知时停止,不切换账号或重试扣时。\n\n' - '可随时关闭;已加入的任务和扣时记录保留。', - ), - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1.closure#1", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1.closure#2", - ); - Navigator.pop(context, true); - }, - child: const Text('同意并开启'), - ), - ], - ); - }, - ); - if (accepted == true && context.mounted) - await service.setEnabled(identity, albumId, confirmed: true); -} - -Future confirmDownloadBatch( - BuildContext context, - DownloadBatch batch, -) async { - AppLog.instance.trace("lib/pages/download_page.dart::confirmDownloadBatch"); - - if (batch.items.isEmpty && batch.albumId == null) { - ScaffoldMessenger.of(context) - .showSnackBar(const SnackBar(content: Text('所选声音已在下载列表中'))); - return false; - } - return await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::confirmDownloadBatch.closure#1", - ); - return AlertDialog( - scrollable: true, - title: Text( - batch.albumId == null ? '下载 ${batch.items.length} 集' : '下载整个专辑', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SizedBox( - width: 480, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (batch.albumId != null) ...[ - Text( - '共 ${batch.albumTotalCount ?? "未知"} 集,首批 ${batch.items.length} 集。' - '当前页处理结束后再请求下一页,单集失败不影响其余声音。', - ), - const SizedBox(height: 8), - const Text('后续每页继续按正常规则逐集扣时;已下载声音自动跳过,可随时暂停。'), - const SizedBox(height: 8), - ], - Text( - batch.totalSeconds == 0 - ? '本批预览无需扣除奖励听时' - : '本批预计扣除 ${batch.totalSeconds} 秒(按实际使用的账号逐集扣除)', - ), - if (batch.totalSeconds > 0) ...[ - const SizedBox(height: 8), - const Text('逐集扣除整首时长,下载失败或取消不自动退回。原任务重试不会重复扣时。'), - ], - if (batch.items.isNotEmpty) const SizedBox(height: 12), - if (batch.items.isNotEmpty) - SizedBox( - height: (batch.items.length * 72.0).clamp(72.0, 260.0), - child: AppScrollbar( - child: ListView.builder( - itemCount: batch.items.length, - itemBuilder: (_, index) { - AppLog.instance.trace( - "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#1", - ); - - final item = batch.items[index]; - return ListTile( - dense: true, - contentPadding: EdgeInsets.zero, - title: Text( - item.track.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - subtitle: Text( - item.error ?? - '${item.accountIdentity != batch.accountIdentity ? "已切换账号 · " : ""}${item.seconds} 秒', - ), - ); - }, - ), - ), - ), - ], - ), - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#2", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#3", - ); - Navigator.pop(context, true); - }, - child: Text(batch.totalSeconds > 0 ? '确认扣时并下载' : '下载'), - ), - ], - ); - }, - ) == - true; -} - -class DownloadPage extends StatefulWidget { - const DownloadPage({required this.runtime, super.key}); - final AppRuntime runtime; - @override - State createState() { - AppLog.instance.trace( - "lib/pages/download_page.dart::DownloadPage.createState", - ); - return _DownloadPageState(); - } -} - -class _DownloadPageState extends State { - DownloadService get _service { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._service.get", - ); - return widget.runtime.downloads; - } - - AutoDownloadService get _autoDownloads { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._autoDownloads.get", - ); - return widget.runtime.autoDownloads; - } - - String? _error; - String? _availabilityKey; - int _availabilityEpoch = 0; - bool _refreshingAvailability = false; - Map _available = const {}; - final _expandedAlbums = {}; - final _selectedDownloads = {}; - bool _selectingDownloads = false, _deletingAudio = false; - bool _removingTasks = false; - final _selectedTasks = {}; - bool _selectingTasks = false; - String _taskFilter = ''; - - bool get _downloadActionsBlocked { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._downloadActionsBlocked.get', - ); - return _removingTasks || - _deletingAudio || - widget.runtime.closing || - widget.runtime.restoringBackup || - widget.runtime.restoreNeedsReload; - } - - int _deletionDone = 0, _deletionTotal = 0; - final _downloadQuery = TextEditingController(); - Timer? _searchDebounce; - String _downloadFilter = ''; - StreamSubscription? _taskChanges; - - @override - void initState() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.initState", - ); - - super.initState(); - _listen(); - } - - void _listen() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._listen", - ); - - _taskChanges = _service.changes.listen((_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._listen.closure#1", - ); - _tasksChanged(); - }); - widget.runtime.albumCache.addListener(_cacheChanged); - unawaited(_refreshAvailability(_service.tasks)); - } - - void _tasksChanged() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._tasksChanged", - ); - - if (!mounted) return; - final tasks = _service.tasks; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._tasksChanged.closure#1", - ); - - _selectedTasks.retainAll({ - for (final task in tasks) - if (task.state != DownloadState.completed) task.id, - }); - if (_selectedDownloads.isNotEmpty) { - _selectedDownloads.retainAll( - tasks.where(_canSelectAudio).map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._tasksChanged.closure#1.closure#1", - ); - return task.id; - }), - ); - } - }); - if (!_deletingAudio) unawaited(_refreshAvailability(tasks)); - } - - void _cacheChanged() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._cacheChanged", - ); - - _availabilityKey = null; - _tasksChanged(); - } - - @override - void didUpdateWidget(covariant DownloadPage oldWidget) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.didUpdateWidget", - ); - - super.didUpdateWidget(oldWidget); - if (oldWidget.runtime == widget.runtime) return; - unawaited(_taskChanges?.cancel()); - oldWidget.runtime.albumCache.removeListener(_cacheChanged); - _availabilityKey = null; - _available = const {}; - _selectedDownloads.clear(); - _selectingDownloads = false; - _selectedTasks.clear(); - _selectingTasks = false; - _listen(); - } - - @override - void dispose() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.dispose", - ); - - _searchDebounce?.cancel(); - _downloadQuery.dispose(); - unawaited(_taskChanges?.cancel()); - widget.runtime.albumCache.removeListener(_cacheChanged); - super.dispose(); - } - - Future _refreshAvailability(List tasks) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability", - ); - - final key = tasks - .map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability.closure#1", - ); - return '${task.id}:${task.finalPath}:${task.state.name}'; - }) - .join('|'); - if (key == _availabilityKey) return; - _availabilityKey = key; - final epoch = ++_availabilityEpoch; - final paths = { - for (final task in tasks) - if (task.finalPath != null) task.id: task.finalPath!, - }; - final result = {}; - for (final entry in paths.entries) { - try { - result[entry.key] = await File(entry.value).exists(); - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'download', - 'Checking audio availability failed', - error: error, - stackTrace: stack, - promptUser: false, - ); - result[entry.key] = false; - } - } - if (mounted && epoch == _availabilityEpoch && key == _availabilityKey) { - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability.closure#2", - ); - _available = result; - }); - } - } - - Future _recheckAvailability() async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability", - ); - - if (_refreshingAvailability || _deletingAudio) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability.closure#1", - ); - _refreshingAvailability = true; - }); - try { - _availabilityKey = null; - await _refreshAvailability(_service.tasks); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability.closure#2", - ); - _refreshingAvailability = false; - }); - } - } - - Future _run( - Future Function() operation, { - bool recoverable = false, - }) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._run", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._run.closure#1", - ); - - if (_downloadActionsBlocked) return; - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#1", - ); - _error = null; - }); - try { - await operation(); - } on XmlyException catch (error, stack) { - _recordDownloadPageError(error, stack); - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#2", - ); - _error = error.message; - }); - } catch (error, stack) { - if (recoverable) { - if (!AppLog.instance.errorWasRecorded(error)) { - AppLog.instance.write( - AppLogLevel.warning, - 'download', - 'Opening download location failed', - error: error, - stackTrace: stack, - promptUser: false, - ); - } - } else { - _recordDownloadPageError(error, stack); - } - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#3", - ); - _error = '操作未完成,请检查任务列表和文件状态后重试'; - }); - } - }); - } - - Future _retry(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._retry", - ); - - task = _service.task(task.id); - if (task.state == DownloadState.completed) { - await _service.retry(task.id); - if (mounted) await _recheckAvailability(); - return; - } - if (task.state == DownloadState.awaitingDebit && task.needsConfirmation) { - // Drain the worker that reported the changed fee before preparing again. - await widget.runtime.pauseDownload(task.id); - task = _service.task(task.id); - } - if (task.state != DownloadState.failed && - task.state != DownloadState.paused && - task.state != DownloadState.cancelled) - return; - if (task.processingFailed) { - await _service.retry(task.id); - return; - } - if (task.needsConfirmation || !task.userConfirmed) { - final batch = await _service.prepareRetry(task.id); - if (!mounted) return; - await _service.enqueue(batch, confirmed: true); - } else { - await _service.retry(task.id); - } - } - - Future _adjustProcessing(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing", - ); - - final media = task.settings['media'] as Map? ?? const {}; - final download = task.settings['download'] as Map? ?? const {}; - final savedFormat = media['format']; - final savedBitrate = media['bitrateKbps']; - final savedConflict = download['conflict']; - var format = - const {'original', 'mp3', 'm4a', 'm4b', 'flac'}.contains(savedFormat) - ? savedFormat as String - : 'original'; - var bitrate = - savedBitrate is int && - const {32, 64, 96, 128, 192}.contains(savedBitrate) - ? savedBitrate - : 64; - var conflict = const {'skip', 'overwrite', 'number'}.contains(savedConflict) - ? savedConflict as String - : 'skip'; - var currentTools = true; - final accepted = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1", - ); - return StatefulBuilder( - builder: (context, update) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1", - ); - return AlertDialog( - title: const Text( - '调整处理', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SingleChildScrollView( - child: SizedBox( - width: 380, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - const Text('仅重跑处理,不重新取流或扣时。'), - DropdownButton( - isExpanded: true, - value: format, - items: const [ - DropdownMenuItem( - value: 'original', - child: Text('原格式'), - ), - DropdownMenuItem(value: 'mp3', child: Text('MP3')), - DropdownMenuItem(value: 'm4a', child: Text('M4A')), - DropdownMenuItem(value: 'm4b', child: Text('M4B')), - DropdownMenuItem(value: 'flac', child: Text('FLAC')), - ], - onChanged: (value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#1", - ); - update(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#1.closure#1", - ); - - format = value!; - }); - }, - ), - if (format != 'original' && format != 'flac') - DropdownButton( - isExpanded: true, - value: bitrate, - items: [ - for (final value in [32, 64, 96, 128, 192]) - DropdownMenuItem( - value: value, - child: Text('$value kbps'), - ), - ], - onChanged: (value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#2", - ); - update(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#2.closure#1", - ); - - bitrate = value!; - }); - }, - ), - DropdownButton( - isExpanded: true, - value: conflict, - items: const [ - DropdownMenuItem( - value: 'skip', - child: Text( - '同名:校验后跳过', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - DropdownMenuItem( - value: 'overwrite', - child: Text( - '同名:新文件完成后替换', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - DropdownMenuItem( - value: 'number', - child: Text( - '同名:自动加编号', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - ], - onChanged: (value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#3", - ); - update(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#3.closure#1", - ); - - conflict = value!; - }); - }, - ), - CheckboxListTile( - contentPadding: EdgeInsets.zero, - value: currentTools, - title: const Text('使用当前工具路径'), - onChanged: (value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#4", - ); - update(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#4.closure#1", - ); - - currentTools = value!; - }); - }, - ), - ], - ), - ), - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#5", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#6", - ); - Navigator.pop(context, true); - }, - child: const Text('保存并重试'), - ), - ], - ); - }, - ); - }, - ); - if (accepted == true) - await _service.reprocess( - task.id, - format: format, - bitrateKbps: bitrate, - conflict: conflict, - useCurrentTools: currentTools, - ); - } - - Future _reacquire(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._reacquire", - ); - - final accepted = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1", - ); - return AlertDialog( - scrollable: true, - title: const Text( - '重新获取音频?', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: Text('${task.track.title}\n清除本任务缓存并重新核验权限,成品和扣时记录会保留。'), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1.closure#1", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1.closure#2", - ); - Navigator.pop(context, true); - }, - child: const Text('重新获取'), - ), - ], - ); - }, - ); - if (accepted != true) return; - await widget.runtime.reacquireDownload(task.id); - } - - Future _relocate(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._relocate", - ); - - final accepted = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1", - ); - return AlertDialog( - scrollable: true, - title: const Text( - '更换目录', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SelectableText( - '${task.track.title}\n${task.rootDirectory}\n旧缓存不自动移动,原扣时记录保留。', - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1.closure#1", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1.closure#2", - ); - Navigator.pop(context, true); - }, - child: const Text('选择目录'), - ), - ], - ); - }, - ); - if (accepted != true) return; - final directory = await FilePicker.getDirectoryPath( - dialogTitle: '选择本任务的下载目录', - ); - if (directory == null) return; - await widget.runtime.relocateDownload(task.id, directory); - } - - void _selectTasks(Iterable tasks) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._selectTasks', - ); - if (_downloadActionsBlocked) return; - final ids = {for (final task in tasks) task.id}; - if (ids.isEmpty) return; - setState(() { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._selectTasks.closure#1', - ); - _selectingTasks = true; - if (ids.every(_selectedTasks.contains)) { - _selectedTasks.removeAll(ids); - } else { - _selectedTasks.addAll(ids); - } - }); - } - - Future _taskBatch(String action) async { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._taskBatch', - ); - if (_downloadActionsBlocked) return; - final selected = [ - for (final task in _service.tasks) - if (_selectedTasks.contains(task.id) && - task.state != DownloadState.completed) - task, - ]; - if (selected.isEmpty) return; - if (action == 'delete') { - await _confirmTaskRemoval(selectedTasks: selected); - return; - } - setState(() { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#1', - ); - _removingTasks = true; - }); - var succeeded = 0; - final failures = []; - try { - for (final task in selected) { - if (!mounted || - widget.runtime.closing || - widget.runtime.restoringBackup || - widget.runtime.restoreNeedsReload) { - failures.add('操作已停止,请先完成退出或备份恢复'); - break; - } - try { - final current = _service.task(task.id); - if (action == 'pause') { - await widget.runtime.pauseDownload(task.id); - } else { - await _retry(current); - final after = _service.task(task.id); - if (after.state != DownloadState.completed && - (!after.active || - after.state == DownloadState.awaitingDebit && - after.needsConfirmation)) { - failures.add('${task.track.title}:未继续,可能已取消确认'); - continue; - } - } - succeeded++; - _selectedTasks.remove(task.id); - } catch (error, stack) { - _recordDownloadPageError(error, stack); - failures.add( - '${task.track.title}:${error is XmlyException ? error.message : '操作失败'}', - ); - } - } - if (mounted) - setState(() { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#2', - ); - _error = - '${action == 'pause' ? '暂停' : '继续'}完成 $succeeded / ${selected.length} 个任务' - '${failures.isEmpty ? '' : ';未完成项保留选中:${failures.join(';')}'}'; - }); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#3', - ); - _removingTasks = false; - }); - } - } - - Widget _taskList(List tasks) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._taskList', - ); - final compact = MediaQuery.sizeOf(context).width < 320; - final visible = tasks.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#1", - ); - return '${task.track.title} ${task.track.album}'.toLowerCase().contains( - _taskFilter, - ); - }).toList(); - final allJobs = _service.albumJobs.where((job) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#2", - ); - return job.state != 'completed' && job.state != 'cancelled'; - }).toList(); - final taskJobs = { - for (final job in allJobs) - for (final id in job.taskIds) id: job.id, - }; - final jobTasks = >{}; - final standalone = []; - for (final task in visible) { - final jobId = taskJobs[task.id]; - if (jobId == null) { - standalone.add(task); - } else { - (jobTasks[jobId] ??= []).add(task); - } - } - final jobs = [ - for (final job in allJobs) - if (job.title.toLowerCase().contains(_taskFilter) || - jobTasks.containsKey(job.id)) - job, - ]; - final hasUnfinished = - tasks.isNotEmpty || - _service.albumJobs.any((job) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#3", - ); - return job.state != 'completed' && job.state != 'cancelled'; - }); - final buttonStyle = OutlinedButton.styleFrom( - minimumSize: const Size(48, 48), - ); - final textStyle = TextButton.styleFrom(minimumSize: const Size(48, 48)); - return LayoutBuilder( - builder: (context, constraints) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4", - ); - return Column( - children: [ - ConstrainedBox( - constraints: BoxConstraints( - maxHeight: math.max(0, constraints.maxHeight - 48), - ), - child: SingleChildScrollView( - primary: false, - child: Padding( - padding: EdgeInsets.all(compact ? 8 : 12), - child: Column( - children: [ - TextField( - key: const ValueKey('downloadTaskSearch'), - decoration: const InputDecoration( - labelText: '搜索任务', - prefixIcon: Icon(Icons.search), - ), - onChanged: (text) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#1", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#1.closure#1", - ); - _taskFilter = text.trim().toLowerCase(); - }); - }, - ), - const SizedBox(height: 8), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Wrap( - spacing: 8, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - for (final (label, icon, action) - in < - (String, IconData, Future Function()) - >[ - ( - '全部暂停', - Icons.pause, - widget.runtime.pauseAllDownloads, - ), - ('全部继续', Icons.download, _service.resumeAll), - ( - '全部取消', - Icons.cancel_outlined, - _confirmTaskRemoval, - ), - ]) - OutlinedButton.icon( - style: buttonStyle, - onPressed: - _downloadActionsBlocked || !hasUnfinished - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#2", - ); - _run(action); - }, - icon: Icon(icon), - label: Text(label), - ), - if (!_selectingTasks) - TextButton.icon( - style: textStyle, - onPressed: - _downloadActionsBlocked || visible.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#3", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#3.closure#1", - ); - _selectingTasks = true; - }); - }, - icon: const Icon(Icons.checklist), - label: const Text('选择任务'), - ) - else ...[ - Text('已选 ${_selectedTasks.length} 个任务'), - TextButton( - style: textStyle, - onPressed: - _downloadActionsBlocked || visible.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#4", - ); - _selectTasks(visible); - }, - child: Text( - _taskFilter.isEmpty - ? '全选/取消全选' - : '搜索结果全选/取消全选', - ), - ), - for (final (action, label) in [ - ('pause', '暂停所选'), - ('resume', '继续所选'), - ('delete', '删除所选任务'), - ]) - OutlinedButton( - style: buttonStyle, - onPressed: - _downloadActionsBlocked || - _selectedTasks.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#5", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#5.closure#1", - ); - return _taskBatch(action); - }); - }, - child: Text(label), - ), - TextButton( - style: textStyle, - onPressed: _downloadActionsBlocked - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#6", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#6.closure#1", - ); - _selectingTasks = false; - _selectedTasks.clear(); - }); - }, - child: const Text('取消多选'), - ), - ], - ], - ), - ), - if (_taskFilter.isNotEmpty) - Text('匹配 ${visible.length} / 共 ${tasks.length} 个任务'), - for (final error in [ - if (_error != null) _error!, - ..._autoDownloads.errors, - ]) - Text( - error, - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - ], - ), - ), - ), - ), - Expanded( - child: AppScrollbar( - child: ListView.builder( - key: const PageStorageKey('compact-download-tasks'), - itemCount: jobs.length + standalone.length, - itemBuilder: (context, index) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#7", - ); - return index < jobs.length - ? _albumJobCard( - jobs[index], - jobTasks[jobs[index].id] ?? const [], - compact, - ) - : _taskCard(standalone[index - jobs.length], compact); - }, - ), - ), - ), - ], - ); - }, - ); - } - - Widget _albumJobCard( - DownloadAlbumJob job, - List tasks, - bool compact, - ) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard', - ); - return ExpansionTile( - key: PageStorageKey('download-album-job:${job.id}'), - minTileHeight: 48, - title: Text(job.title, maxLines: 1, overflow: TextOverflow.ellipsis), - children: [ - Text('整专辑 · ${job.state} · 第 ${job.page} 页 / ${job.total} 集'), - if (job.error != null) - Text( - job.error!, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - AdaptiveText('账号:${job.accountIdentity}'), - AdaptiveText('目录:${job.rootDirectory}'), - Wrap( - spacing: 8, - runSpacing: 4, - children: [ - for (final (label, action) in <(String, Future Function())>[ - if (job.state == 'running') - ( - '暂停专辑', - () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#1", - ); - return _service.pauseAlbum(job.id); - }, - ), - if (job.state != 'running') - ( - '继续专辑', - () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#2", - ); - return _service.resumeAlbum(job.id); - }, - ), - if (job.state != 'running') - ( - '刷新专辑', - () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#3", - ); - return _service.refreshAlbum(job.id); - }, - ), - ( - '取消专辑任务', - () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#4", - ); - return _cancelAlbum(job.id); - }, - ), - ]) - TextButton( - style: TextButton.styleFrom(minimumSize: const Size(48, 48)), - onPressed: _downloadActionsBlocked - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#5", - ); - _run(action); - }, - child: Text(label), - ), - ], - ), - if (tasks.isNotEmpty) - SizedBox( - height: (tasks.length * 48.0).clamp(48.0, 400.0).toDouble(), - child: ListView.builder( - primary: false, - itemCount: tasks.length, - itemBuilder: (_, index) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#6', - ); - return _taskCard(tasks[index], compact); - }, - ), - ), - ], - ); - } - - Future _cancel(DownloadTask task) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._cancel', - ); - return _confirmTaskRemoval(task: task); - } - - Future _confirmTaskRemoval({ - DownloadTask? task, - String? albumId, - List? selectedTasks, - }) async { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval', - ); - if (_downloadActionsBlocked) return; - setState(() { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#1', - ); - _removingTasks = true; - }); - try { - final all = task == null && albumId == null && selectedTasks == null; - final confirmed = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2', - ); - return AlertDialog( - scrollable: true, - title: Text( - task != null - ? '删除此任务?' - : selectedTasks != null - ? '删除选中的 ${selectedTasks.length} 个任务?' - : all - ? '全部取消?' - : '取消整专辑下载?', - ), - content: Text( - task != null - ? '停止并永久删除此任务记录,不能再恢复任务。已下载文件、缓存和扣时记录保留,不自动退款。${task.state == DownloadState.completed ? '此记录也会从“已下载”列表移除,磁盘音频不会删除。' : ''}' - : selectedTasks != null - ? '停止并永久删除选中的任务记录,不能恢复任务。已下载文件、缓存和扣时记录保留,不自动退款。' - : '停止${all ? '所有' : '此专辑的'}后续分页,永久删除${all ? '全部' : '此专辑的'}未完成任务。已完成记录、已下载文件、缓存和扣时记录保留,不自动退款。', - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2.closure#1', - ); - Navigator.pop(context, false); - }, - child: const Text('返回'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2.closure#2', - ); - Navigator.pop(context, true); - }, - child: Text( - task != null || selectedTasks != null - ? '删除任务' - : all - ? '全部取消' - : '取消专辑任务', - ), - ), - ], - ); - }, - ); - if (confirmed != true || !mounted) return; - if (task != null) { - await widget.runtime.cancelDownload(task.id); - } else if (selectedTasks != null) { - await widget.runtime.cancelDownloads( - selectedTasks.map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#3", - ); - return task.id; - }), - ); - } else if (albumId != null) { - await widget.runtime.cancelAlbumDownloads(albumId); - } else { - await widget.runtime.cancelAllDownloads(); - } - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#4", - ); - _removingTasks = false; - }); - } - } - - Future _open(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._open", - ); - - final path = task.finalPath == null - ? task.rootDirectory - : p.dirname(task.finalPath!); - if (!await Directory(path).exists()) - throw const FileSystemException('Directory missing'); - if (Platform.isAndroid) { - if (task.finalPath case final file?) { - await AndroidPlatform.openAudioFile(file); - } else if (mounted) { - await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._open.closure#1", - ); - return AlertDialog( - scrollable: true, - title: const Text( - '下载目录', - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - content: SelectableText(path), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._open.closure#1.closure#1", - ); - Navigator.pop(context); - }, - child: const Text('关闭'), - ), - ], - ); - }, - ); - } - return; - } - final executable = Platform.isWindows - ? 'explorer.exe' - : Platform.isMacOS - ? 'open' - : 'xdg-open'; - await Process.start(executable, [path], runInShell: false); - } - - Future _delete(DownloadTask task) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._delete", - ); - - if (_deletingAudio) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._delete.closure#1", - ); - _deletingAudio = true; - }); - try { - if (await deleteDownloadedAudio(context, widget.runtime, task)) { - _availabilityKey = null; - await _refreshAvailability(_service.tasks); - } - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._delete.closure#2", - ); - _deletingAudio = false; - }); - } - } - - bool _canSelectAudio(DownloadTask task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._canSelectAudio", - ); - return task.state == DownloadState.completed && task.finalPath != null; - } - - void _selectAudio(Iterable tasks) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._selectAudio", - ); - - if (_deletingAudio) return; - final ids = tasks.where(_canSelectAudio).map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._selectAudio.closure#1", - ); - return task.id; - }).toSet(); - if (ids.isEmpty) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._selectAudio.closure#2", - ); - - _selectingDownloads = true; - if (ids.every(_selectedDownloads.contains)) { - _selectedDownloads.removeAll(ids); - } else { - _selectedDownloads.addAll(ids); - } - }); - } - - Future _deleteSelectedAudio() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1", - ); - - if (_deletingAudio || _selectedDownloads.isEmpty) return; - final runtime = widget.runtime; - final groups = >{}; - for (final task in _service.tasks.where(_canSelectAudio)) { - if (_selectedDownloads.contains(task.id)) { - groups - .putIfAbsent(_audioPathKey(task.finalPath!), () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#1", - ); - return []; - }) - .add(task); - } - } - if (groups.isEmpty) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#2", - ); - - _deletingAudio = true; - _deletionDone = 0; - _deletionTotal = 0; - }); - try { - var estimatedBytes = 0, unknownSizes = 0; - for (final tasks in groups.values) { - try { - final stat = await File(tasks.first.finalPath!).stat(); - if (stat.type == FileSystemEntityType.file) { - estimatedBytes += stat.size; - } else { - unknownSizes++; - } - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'download', - 'Estimating audio size failed', - error: error, - stackTrace: stack, - promptUser: false, - ); - unknownSizes++; - } - } - if (!mounted || widget.runtime != runtime) return; - final selected = groups.values.fold>([], ( - selected, - tasks, - ) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#3", - ); - selected.addAll(tasks); - return selected; - }); - final count = selected.length; - final hiddenSelected = - count - _matchingDownloads(selected, _downloadFilter).length; - final confirmed = await showDialog( - context: context, - builder: (context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4", - ); - return AlertDialog( - scrollable: true, - title: Text('删除 $count 条声音的音频?'), - content: Text( - '共 ${groups.length} 个路径,预计释放 ${_bytes(estimatedBytes)}' - '${unknownSizes > 0 ? "(另有 $unknownSizes 个路径大小未知或文件已缺失)" : ""}。\n\n' - '${hiddenSelected > 0 ? "其中 $hiddenSelected 条已选声音不在当前搜索结果中,也将删除其音频。\n\n" : ""}' - '正在使用这些文件的播放会停止。任务和扣时记录保留;缺失文件不会记为主动删除。', - ), - actions: [ - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4.closure#1", - ); - Navigator.pop(context, false); - }, - child: const Text('取消'), - ), - FilledButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4.closure#2", - ); - Navigator.pop(context, true); - }, - child: const Text('删除所选音频'), - ), - ], - ); - }, - ); - if (confirmed != true || !mounted || widget.runtime != runtime) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#5", - ); - _deletionTotal = groups.length; - }); - var freedBytes = 0, deletedFiles = 0; - final failures = []; - final cleared = {}; - for (final tasks in groups.values) { - try { - await _deleteAudioGroup( - runtime, - tasks, - onDeleted: (bytes) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#6", - ); - - freedBytes += bytes; - deletedFiles++; - }, - ); - cleared.addAll( - tasks.map((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#7", - ); - return task.id; - }), - ); - } catch (error, stack) { - _recordDownloadPageError(error, stack); - failures.add( - '${tasks.first.track.title}:${error is XmlyException ? error.message : "删除或记录更新未完成,请刷新后重试"}', - ); - } - if (mounted && widget.runtime == runtime) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#8", - ); - _deletionDone++; - }); - } - if (!mounted || widget.runtime != runtime) return; - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#9", - ); - - _selectedDownloads.removeAll(cleared); - if (_selectedDownloads.isEmpty) _selectingDownloads = false; - _error = failures.isEmpty - ? null - : '${failures.length} 个路径未完全处理;已删除文件不会恢复。\n${failures.take(3).join("\n")}'; - }); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - '已删除 $deletedFiles 个文件,释放 ${_bytes(freedBytes)};${failures.length} 项未完成', - ), - ), - ); - _availabilityKey = null; - await _refreshAvailability(_service.tasks); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#10", - ); - _deletingAudio = false; - }); - } - }); - } - - Future _openAlbum(String albumId) async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._openAlbum", - ); - - await Navigator.of(context).push( - MaterialPageRoute( - builder: (_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._openAlbum.closure#1", - ); - return AlbumPageView( - runtime: widget.runtime, - albumId: albumId, - onDownload: (tracks) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._openAlbum.closure#1.closure#1", - ); - return requestDownloads(context, widget.runtime, tracks); - }, - onPlayAlbum: widget.runtime.player.playAlbum, - ); - }, - ), - ); - if (!mounted) return; - _availabilityKey = null; - await _refreshAvailability(_service.tasks); - } - - Widget _albumCard( - String albumId, - List tasks, - bool compact, { - required bool downloaded, - }) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard", - ); - - final cached = albumId.isEmpty ? null : widget.runtime.albumCache[albumId]; - final album = cached?.album; - final total = album?.total ?? 0; - late final completed = { - for (final task in tasks) - if (_available[task.id] == true) task.track.id, - }.length; - final missing = downloaded - ? tasks.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#1", - ); - return task.finalPath == null || _available[task.id] == false; - }).length - : 0; - final states = {}; - for (final task in tasks) { - states.update( - task.state, - (count) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#2", - ); - return count + 1; - }, - ifAbsent: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#3", - ); - return 1; - }, - ); - } - final summary = [ - for (final entry in states.entries) '${_state(entry.key)} ${entry.value}', - if (missing > 0) '文件缺失 $missing', - ].join(' · '); - final title = albumId.isEmpty - ? '未归属专辑的声音' - : album != null && album.title.isNotEmpty - ? album.title - : tasks.first.track.album.isNotEmpty - ? tasks.first.track.album - : '专辑 $albumId'; - final expansionKey = '${downloaded ? 'downloaded' : 'tasks'}:$albumId'; - final expanded = _expandedAlbums.contains(expansionKey); - late final selectable = tasks.where(_canSelectAudio).toList(); - late final selected = selectable.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#4", - ); - return _selectedDownloads.contains(task.id); - }).length; - final selecting = downloaded && _selectingDownloads; - void toggle() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.toggle", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.toggle.closure#1", - ); - - if (expanded) { - _expandedAlbums.remove(expansionKey); - } else { - _expandedAlbums.add(expansionKey); - } - }); - } - - return Card( - margin: EdgeInsets.symmetric(horizontal: compact ? 8 : 16, vertical: 6), - child: Column( - children: [ - ListTile( - contentPadding: EdgeInsets.symmetric( - horizontal: compact ? 8 : 16, - vertical: 6, - ), - leading: selecting - ? Checkbox( - tristate: true, - value: selected == 0 - ? false - : selected == selectable.length - ? true - : null, - onChanged: _deletingAudio || selectable.isEmpty - ? null - : (_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#5", - ); - _selectAudio(selectable); - }, - ) - : compact - ? null - : CoverImage( - uri: album?.coverUrl ?? tasks.first.track.coverUrl, - localPath: cached?.coverPath, - size: 52, - downloaded: downloaded && completed > 0, - ), - title: Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - ), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (downloaded) - Text( - '$completed / ${total > 0 ? total : "总集数未知"} 集已下载', - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - ), - if (downloaded && total > 0) - Padding( - padding: const EdgeInsets.symmetric(vertical: 4), - child: LinearProgressIndicator( - value: (completed / total).clamp(0.0, 1.0), - ), - ), - Text( - summary, - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - ), - ], - ), - onTap: selecting - ? (_deletingAudio - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#6", - ); - _selectAudio(selectable); - }) - : albumId.isEmpty - ? toggle - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#7", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#7.closure#1", - ); - return _openAlbum(albumId); - }); - }, - onLongPress: downloaded && !_deletingAudio - ? () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#8", - ); - _selectAudio(selectable); - } - : null, - trailing: IconButton( - tooltip: expanded ? '收起声音与操作' : '展开声音与操作', - icon: Icon(expanded ? Icons.expand_less : Icons.expand_more), - onPressed: toggle, - ), - ), - if (expanded) ...[ - const Divider(height: 1), - SizedBox( - height: (tasks.length * (downloaded ? 80.0 : 260.0)) - .clamp(80.0, 400.0) - .toDouble(), - child: ListView.builder( - primary: false, - itemCount: tasks.length, - itemBuilder: (_, index) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#9", - ); - return downloaded - ? _downloadedTrack(tasks[index], compact) - : _taskCard(tasks[index], compact); - }, - ), - ), - ], - ], - ), - ); - } - - Widget _downloadedTrack( - DownloadTask task, - bool compact, { - bool searchResult = false, - }) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack", - ); - - final available = _available[task.id] == true; - return ListTile( - selected: _selectingDownloads && _selectedDownloads.contains(task.id), - leading: _selectingDownloads - ? Checkbox( - value: _selectedDownloads.contains(task.id), - onChanged: _deletingAudio || !_canSelectAudio(task) - ? null - : (_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#1", - ); - _selectAudio([task]); - }, - ) - : compact - ? null - : CoverImage( - uri: searchResult ? null : task.track.coverUrl, - localPath: task.track.albumId.isEmpty - ? null - : widget.runtime.albumCache[task.track.albumId]?.coverPath, - downloaded: available, - size: 44, - ), - title: AdaptiveText(task.track.title), - subtitle: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - if (searchResult) - Text( - _downloadAlbumTitle(task), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - Text( - _available.containsKey(task.id) - ? (available ? '已下载' : '音频文件已不存在') - : '正在检查本地文件', - ), - ], - ), - onLongPress: _deletingAudio - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#2", - ); - _selectAudio([task]); - }, - onTap: _deletingAudio - ? null - : _selectingDownloads - ? () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#3", - ); - _selectAudio([task]); - } - : available - ? () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#4", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#4.closure#1", - ); - return widget.runtime.player.playLocal(task.id); - }); - } - : null, - trailing: PopupMenuButton( - enabled: !_downloadActionsBlocked && !_selectingDownloads, - tooltip: '已下载声音操作', - onSelected: (action) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#5", - ); - _run(() async { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#5.closure#1", - ); - - switch (action) { - case 'play': - await widget.runtime.player.playLocal(task.id); - case 'next': - await widget.runtime.player.playNext(task.track); - case 'retry': - await _retry(task); - case 'open': - await _open(task); - case 'delete': - await _delete(task); - case 'remove': - await _cancel(task); - } - }, recoverable: action == 'open'); - }, - itemBuilder: (_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#6", - ); - return [ - if (available) - const PopupMenuItem(value: 'play', child: Text('播放')), - if (available) - const PopupMenuItem(value: 'next', child: Text('下一集播放')), - if (_available[task.id] == false) - const PopupMenuItem(value: 'retry', child: Text('重新下载')), - const PopupMenuItem(value: 'open', child: Text('打开目录')), - if (available) - const PopupMenuItem(value: 'delete', child: Text('删除音频')), - const PopupMenuItem(value: 'remove', child: Text('删除任务')), - ]; - }, - ), - ); - } - - Future _cancelAlbum(String id) { - AppLog.instance.trace( - 'lib/pages/download_page.dart::_DownloadPageState._cancelAlbum', - ); - return _confirmTaskRemoval(albumId: id); - } - - String _downloadAlbumTitle(DownloadTask task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadAlbumTitle", - ); - - final id = task.track.albumId; - final cached = id.isEmpty - ? null - : widget.runtime.albumCache[id]?.album.title; - if (cached != null && cached.isNotEmpty) return cached; - if (task.track.album.isNotEmpty) return task.track.album; - return id.isEmpty ? '未归属专辑的声音' : '专辑 $id'; - } - - void _searchDownloads(String text, {bool immediately = false}) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._searchDownloads", - ); - - _searchDebounce?.cancel(); - void apply() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._searchDownloads.apply", - ); - - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._searchDownloads.apply.closure#1", - ); - _downloadFilter = text.trim().toLowerCase(); - }); - } - - if (immediately) { - apply(); - } else { - _searchDebounce = Timer(const Duration(milliseconds: 180), apply); - } - } - - List _matchingDownloads( - List tasks, - String query, - ) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads", - ); - if (query.isEmpty) return tasks; - final tokens = query.split(RegExp(r'\s+')).where((value) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads.closure#1", - ); - return value.isNotEmpty; - }); - return tasks.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads.closure#2", - ); - final track = task.track; - final text = [ - _downloadAlbumTitle(task), - track.album, - track.title, - for (final ordinal in { - track.officialPosition, - track.orderNo, - track.episode, - }.whereType()) - '$ordinal 第${ordinal}集', - ].join(' ').toLowerCase(); - return tokens.every(text.contains); - }).toList(); - } - - Widget _downloadedLibrary(List completed) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary", - ); - - final compact = MediaQuery.sizeOf(context).width < 320; - final query = _downloadFilter; - final visible = _matchingDownloads(completed, query); - final hiddenSelected = query.isEmpty || _selectedDownloads.isEmpty - ? 0 - : _selectedDownloads.length - - visible.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#1", - ); - return _selectedDownloads.contains(task.id); - }).length; - return LayoutBuilder( - builder: (context, constraints) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2", - ); - return Column( - children: [ - ConstrainedBox( - constraints: BoxConstraints( - maxHeight: math.max(0, constraints.maxHeight - 96), - ), - child: SingleChildScrollView( - primary: false, - child: Column( - children: [ - Padding( - padding: EdgeInsets.fromLTRB( - compact ? 8 : 16, - 12, - compact ? 8 : 16, - 8, - ), - child: TextField( - key: const ValueKey('downloadLibrarySearch'), - controller: _downloadQuery, - decoration: InputDecoration( - labelText: '搜索已下载', - hintText: '专辑、单集标题或集号', - prefixIcon: const Icon(Icons.search), - suffixIcon: ValueListenableBuilder( - valueListenable: _downloadQuery, - builder: (context, value, _) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#1", - ); - return value.text.isEmpty - ? const SizedBox.shrink() - : IconButton( - tooltip: '清除本地搜索', - icon: const Icon(Icons.clear), - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#1.closure#1", - ); - _downloadQuery.clear(); - _searchDownloads('', immediately: true); - }, - ); - }, - ), - ), - textInputAction: TextInputAction.search, - onChanged: _searchDownloads, - onSubmitted: (text) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#2", - ); - _searchDownloads(text, immediately: true); - }, - ), - ), - Wrap( - spacing: 8, - runSpacing: 8, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - OutlinedButton.icon( - onPressed: - _refreshingAvailability || - _deletingAudio || - completed.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#3", - ); - _run(_recheckAvailability); - }, - icon: _refreshingAvailability - ? const SizedBox.square( - dimension: 18, - child: CircularProgressIndicator( - strokeWidth: 2, - ), - ) - : const Icon(Icons.refresh), - label: Text( - _refreshingAvailability ? '正在检查' : '刷新本地文件', - ), - ), - if (!_selectingDownloads) - OutlinedButton.icon( - onPressed: _deletingAudio || visible.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#4", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#4.closure#1", - ); - _selectingDownloads = true; - }); - }, - icon: const Icon(Icons.checklist), - label: const Text('多选音频'), - ) - else ...[ - Text( - '已选 ${_selectedDownloads.length} 条' - '${hiddenSelected > 0 ? "(含 $hiddenSelected 条未显示)" : ""}', - ), - TextButton( - onPressed: _deletingAudio || visible.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#5", - ); - _selectAudio(visible); - }, - child: Text( - query.isEmpty ? '全选/取消全选' : '搜索结果全选/取消全选', - ), - ), - FilledButton.icon( - onPressed: - _deletingAudio || _selectedDownloads.isEmpty - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#6", - ); - _run(_deleteSelectedAudio); - }, - icon: const Icon(Icons.delete_outline), - label: const Text('删除所选音频'), - ), - TextButton( - onPressed: _deletingAudio - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#7", - ); - setState(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#7.closure#1", - ); - _selectingDownloads = false; - _selectedDownloads.clear(); - }); - }, - child: const Text('取消多选'), - ), - ], - ], - ), - if (_deletingAudio) ...[ - LinearProgressIndicator( - value: _deletionTotal == 0 - ? null - : _deletionDone / _deletionTotal, - ), - Text( - _deletionTotal == 0 - ? '正在准备删除' - : '正在处理 $_deletionDone / $_deletionTotal 个路径', - ), - ], - if (query.isNotEmpty) - Padding( - padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), - child: Text( - '本地下载记录:匹配 ${visible.length} / 共 ${completed.length} 条', - ), - ), - if (query.isNotEmpty && _error != null) - Padding( - padding: const EdgeInsets.all(8), - child: Text( - _error!, - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - ), - ], - ), - ), - ), - Expanded( - child: query.isEmpty - ? _albumList(completed, downloaded: true) - : visible.isEmpty - ? const Center(child: Text('未找到匹配的本地下载记录')) - : AppScrollbar( - child: ListView.builder( - key: ValueKey('downloadSearch:$query'), - itemCount: visible.length, - itemBuilder: (context, index) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#8", - ); - return _downloadedTrack( - visible[index], - compact, - searchResult: true, - ); - }, - ), - ), - ), - ], - ); - }, - ); - } - - Widget _albumList(Iterable tasks, {required bool downloaded}) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumList", - ); - - final compact = MediaQuery.sizeOf(context).width < 320; - final groups = >{}; - for (final task in tasks) { - groups - .putIfAbsent(task.track.albumId, () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#1", - ); - return []; - }) - .add(task); - } - if (downloaded) { - for (final group in groups.entries) { - if (group.key.isEmpty) continue; - final originalOrder = { - for (var index = 0; index < group.value.length; index++) - group.value[index].id: index, - }; - int? position(DownloadTask task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumList.position", - ); - return task.track.officialPosition ?? - xmlyPositive(task.track.orderNo) ?? - xmlyPositive(task.track.episode); - } - - group.value.sort((a, b) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#2", - ); - - final left = position(a), right = position(b); - if (left != null && right != null && left != right) { - return left.compareTo(right); - } - if ((left == null) != (right == null)) return left == null ? 1 : -1; - return originalOrder[a.id]!.compareTo(originalOrder[b.id]!); - }); - } - } - final albums = groups.entries.toList(); - return AppScrollbar( - child: ListView.builder( - key: PageStorageKey( - downloaded ? 'downloaded-albums' : 'download-tasks', - ), - itemCount: albums.length + 1, - itemBuilder: (context, index) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#3", - ); - - if (index > 0) { - final group = albums[index - 1]; - return _albumCard( - group.key, - group.value, - compact, - downloaded: downloaded, - ); - } - return Padding( - padding: EdgeInsets.all(compact ? 8 : 16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - for (final error in [if (_error != null) _error!]) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text( - error, - style: TextStyle( - color: Theme.of(context).colorScheme.error, - ), - ), - ), - if (albums.isEmpty) - Padding( - padding: const EdgeInsets.symmetric(vertical: 24), - child: Center( - child: Text(downloaded ? '暂无已下载内容' : '暂无下载任务'), - ), - ), - ], - ), - ); - }, - ), - ); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.build", - ); - return StreamBuilder( - stream: _autoDownloads.changes, - builder: (context, _) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.build.closure#1", - ); - - final tasks = _service.tasks; - final completed = tasks.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.build.closure#1.closure#1", - ); - return task.state == DownloadState.completed; - }).toList(); - return DefaultTabController( - length: 2, - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 720), - child: Column( - children: [ - const TabBar( - tabs: [ - Tab(text: '下载任务'), - Tab(text: '已下载'), - ], - ), - Expanded( - child: TabBarView( - children: [ - _taskList( - tasks.where((task) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState.build.closure#1.closure#2", - ); - return task.state != DownloadState.completed; - }).toList(), - ), - _downloadedLibrary(completed), - ], - ), - ), - ], - ), - ), - ), - ); - }, - ); - } - - Widget _taskCard(DownloadTask task, bool compact) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard", - ); - - final total = task.totalBytes; - final progress = total == null || total <= 0 - ? null - : (task.receivedBytes / total).clamp(0.0, 1.0); - final remaining = total == null || task.bytesPerSecond <= 0 - ? null - : ((total - task.receivedBytes).clamp(0, total) / task.bytesPerSecond) - .ceil(); - return ExpansionTile( - key: PageStorageKey('download-task:${task.id}'), - minTileHeight: 48, - tilePadding: EdgeInsets.symmetric(horizontal: compact ? 8 : 16), - childrenPadding: EdgeInsets.fromLTRB( - compact ? 8 : 16, - 0, - compact ? 8 : 16, - 12, - ), - leading: _selectingTasks - ? Checkbox( - value: _selectedTasks.contains(task.id), - onChanged: _downloadActionsBlocked - ? null - : (_) { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#1", - ); - _selectTasks([task]); - }, - ) - : null, - title: Text( - task.track.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - children: [ - Text( - '${task.track.album} · ${_state(task.state)}', - maxLines: 1, - overflow: TextOverflow.ellipsis, - textAlign: TextAlign.center, - ), - AdaptiveText('账号:${task.accountIdentity}'), - AdaptiveText('目录:${task.finalPath ?? task.rootDirectory}'), - if (task.error != null) - Text( - task.error!, - style: TextStyle(color: Theme.of(context).colorScheme.error), - ), - if (task.state == DownloadState.downloading || - task.state == DownloadState.processing) ...[ - const SizedBox(height: 12), - LinearProgressIndicator( - value: task.state == DownloadState.processing ? null : progress, - ), - ], - const SizedBox(height: 8), - AdaptiveText( - '${_bytes(task.receivedBytes)} / ${total == null ? "未知" : _bytes(total)} · ${_bytes(task.bytesPerSecond.round())}/s${remaining == null ? "" : " · 剩余 ${remaining}s"}', - ), - if (task.retryAt != null) - AdaptiveText( - '下次重试 ${task.retryAt!.toLocal().toString().split(".").first}', - ), - if (task.actualQuality != null) - AdaptiveText('实际音质:${task.actualQuality}'), - if (task.warning != null) - Text( - task.warning!, - style: TextStyle(color: Theme.of(context).colorScheme.tertiary), - ), - Wrap( - alignment: WrapAlignment.center, - spacing: 8, - runSpacing: 8, - children: [ - if (task.state == DownloadState.awaitingDebit && - task.needsConfirmation) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#2", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#2.closure#1", - ); - return _retry(task); - }); - }, - child: const Text('重新获取'), - ), - if (task.active && - !(task.state == DownloadState.awaitingDebit && - task.needsConfirmation)) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#3", - ); - - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#3.closure#1", - ); - return widget.runtime.pauseDownload(task.id); - }); - }, - child: const Text('暂停'), - ), - if (task.state == DownloadState.paused) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#4", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#4.closure#1", - ); - return _retry(task); - }); - }, - child: Text( - task.needsConfirmation && !task.processingFailed - ? '重新获取' - : '继续', - ), - ), - if (task.state == DownloadState.failed) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#5", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#5.closure#1", - ); - return _retry(task); - }); - }, - child: Text( - task.needsConfirmation - ? '重新获取' - : task.processingFailed - ? '重试处理' - : '重试', - ), - ), - if (task.state == DownloadState.cancelled) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#6", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#6.closure#1", - ); - return _retry(task); - }); - }, - child: Text(task.processingFailed ? '恢复并重试处理' : '恢复任务'), - ), - if (task.processingFailed && - (task.state == DownloadState.failed || - task.state == DownloadState.paused || - task.state == DownloadState.cancelled)) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#7", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#7.closure#1", - ); - return _reacquire(task); - }); - }, - child: const Text('重新获取音频'), - ), - if (task.processingFailed && - (task.state == DownloadState.failed || - task.state == DownloadState.paused || - task.state == DownloadState.cancelled)) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#8", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#8.closure#1", - ); - return _adjustProcessing(task); - }); - }, - child: const Text('调整处理'), - ), - TextButton( - onPressed: _downloadActionsBlocked - ? null - : () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#9", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#9.closure#1", - ); - return _cancel(task); - }); - }, - child: const Text('删除任务'), - ), - if (!task.active && task.state != DownloadState.completed) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#10", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#10.closure#1", - ); - return _relocate(task); - }); - }, - child: const Text('更换目录'), - ), - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#11", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#11.closure#1", - ); - return _open(task); - }, recoverable: true); - }, - child: const Text('打开目录'), - ), - if (task.finalPath != null) - TextButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#12", - ); - _run(() { - AppLog.instance.trace( - "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#12.closure#1", - ); - return _delete(task); - }); - }, - child: const Text('删除音频'), - ), - ], - ), - ], - ); - } -} - -String _bytes(int value) { - AppLog.instance.trace("lib/pages/download_page.dart::_bytes"); - return value < 1024 - ? '${value}B' - : value < 1024 * 1024 - ? '${(value / 1024).toStringAsFixed(1)}KiB' - : '${(value / (1024 * 1024)).toStringAsFixed(1)}MiB'; -} - -String _state(DownloadState state) { - AppLog.instance.trace("lib/pages/download_page.dart::_state"); - return switch (state) { - DownloadState.queued => '等待中', - DownloadState.awaitingDebit => '等待扣时确认', - DownloadState.downloading => '下载中', - DownloadState.paused => '已暂停', - DownloadState.processing => '处理中', - DownloadState.completed => '已完成', - DownloadState.failed => '失败', - DownloadState.cancelled => '已取消', - }; -} +import 'dart:async'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:path/path.dart' as p; +import 'package:file_picker/file_picker.dart'; + +import '../common/widgets/app_scrollbar.dart'; +import '../common/widgets/adaptive_text.dart'; +import '../services/app_runtime.dart'; +import '../services/app_log.dart'; +import '../services/account_service.dart'; +import '../storage/app_storage.dart'; +import '../services/download_service.dart'; +import '../models/xmly_models.dart'; +import '../services/auto_download_service.dart'; +import '../services/android_platform.dart'; +import '../services/file_paths.dart'; +import 'catalogue_page.dart'; + +void _recordDownloadPageError(Object error, StackTrace stack) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_recordDownloadPageError", + ); + + if (error is DownloadStopped || + (error is StorageException && + const {'too_large', 'secret_in_state'}.contains(error.code)) || + (error is AccountException && + const { + 'credential_missing', + 'missing', + 'paused', + 'closed', + 'not_loaded', + 'credential_mismatch', + 'archive_invalid', + 'quota_invalid', + 'unsettled', + }.contains(error.code)) || + (error is XmlyException && + const { + 'invalid_id', + 'invalid_credentials', + 'invalid_quality', + 'invalid_retry', + 'invalid_settings', + 'invalid_duration', + 'invalid_space', + 'invalid_conflict', + 'media_format', + 'media_bitrate', + 'media_settings', + 'media_tags', + 'receipt_required', + 'cache_paused', + 'cache_closed', + 'login_required', + 'login_expired', + 'auth_required', + 'missing_account', + 'confirmation_required', + 'confirmation_changed', + 'insufficient_quota', + 'usage_uncertain', + 'original_account_required', + 'task_busy', + 'task_missing', + 'batch_invalid', + 'batch_too_large', + 'catalogue_limit', + 'download_changed', + 'shared_audio', + 'audio_changed', + 'closed', + 'client_closed', + 'request_cancelled', + }.contains(error.code)) || + AppLog.instance.errorWasRecorded(error)) + return; + AppLog.instance.write( + AppLogLevel.error, + 'download', + 'Download page action failed', + error: error, + stackTrace: stack, + promptUser: true, + ); +} + +Future<({String identity, bool polling})?> _chooseDownloadAccount( + BuildContext context, + AppRuntime runtime, +) async { + AppLog.instance.trace("lib/pages/download_page.dart::_chooseDownloadAccount"); + + final primary = runtime.accounts.primaryAccountId ?? 'anonymous'; + final accountIds = runtime.accounts.accountIds; + var polling = + ((runtime.storage.state['settings'] as Map)['download'] + as Map?)?['polling'] != + false; + if (accountIds.isEmpty) return (identity: 'anonymous', polling: false); + final selected = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1", + ); + return StatefulBuilder( + builder: (context, setState) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1", + ); + return SimpleDialog( + title: const Text('下载账号'), + children: [ + SwitchListTile( + title: const Text('轮询'), + subtitle: const Text('请求失败时尝试下一个账号;扣时结果不明时停止'), + value: polling, + onChanged: (value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#1", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#1.closure#1", + ); + polling = value; + }); + }, + ), + for (final id in accountIds) + SimpleDialogOption( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#2", + ); + Navigator.pop(context, id); + }, + child: Text( + '账号 ${(runtime.storage.state['accounts'] as Map)[id]['uid']}' + '${id == primary ? ' · 主账号' : ''}', + ), + ), + SimpleDialogOption( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#1.closure#1.closure#3", + ); + Navigator.pop(context, 'anonymous'); + }, + child: const Text('不登录(免费内容)'), + ), + ], + ); + }, + ); + }, + ); + if (selected == null) return null; + await runtime.storage.transaction((state) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#2", + ); + + final settings = state['settings'] as Map; + final download = settings.putIfAbsent('download', () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_chooseDownloadAccount.closure#2.closure#1", + ); + return {}; + }) as Map; + download['polling'] = polling; + }); + return (identity: selected, polling: selected != 'anonymous' && polling); +} + +Future requestDownloads( + BuildContext context, + AppRuntime runtime, + List tracks, { + String? accountIdentity, +}) async { + AppLog.instance.trace("lib/pages/download_page.dart::requestDownloads"); + + final account = accountIdentity == null + ? await _chooseDownloadAccount(context, runtime) + : (identity: accountIdentity, polling: false); + if (account == null || !context.mounted) return; + final batch = await runtime.prepareDownloads( + tracks, + accountIdentity: account.identity, + polling: account.polling, + previewBilling: false, + ); + if (!context.mounted) return; + if (batch.items.isEmpty) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text('所选声音已在下载列表中'))); + return; + } + await runtime.downloads.enqueue(batch, confirmed: true); +} + +Future requestAlbumDownloads( + BuildContext context, + AppRuntime runtime, + String albumId, { + String? accountIdentity, +}) async { + AppLog.instance.trace("lib/pages/download_page.dart::requestAlbumDownloads"); + + final account = accountIdentity == null + ? await _chooseDownloadAccount(context, runtime) + : (identity: accountIdentity, polling: false); + if (account == null || !context.mounted) return; + final batch = await runtime.prepareAlbumDownloads( + albumId, + accountIdentity: account.identity, + polling: account.polling, + ); + if (!context.mounted) return; + await runtime.downloads.enqueue(batch, confirmed: true); +} + +Future deleteDownloadedAudio( + BuildContext context, + AppRuntime runtime, + DownloadTask task, +) async { + AppLog.instance.trace("lib/pages/download_page.dart::deleteDownloadedAudio"); + + final path = task.finalPath; + if (path == null) return false; + final confirmed = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1", + ); + return AlertDialog( + scrollable: true, + title: const Text( + '删除音频文件?', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SelectableText(path), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1.closure#1", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::deleteDownloadedAudio.closure#1.closure#2", + ); + Navigator.pop(context, true); + }, + child: const Text('删除文件'), + ), + ], + ); + }, + ); + if (confirmed != true) return false; + await _deleteAudioGroup(runtime, [task]); + return true; +} + +String _audioPathKey(String path) { + AppLog.instance.trace("lib/pages/download_page.dart::_audioPathKey"); + return Platform.isWindows + ? absoluteFilePath(path).toLowerCase() + : absoluteFilePath(path); +} + +Future _deleteAudioGroup( + AppRuntime runtime, + List tasks, { + void Function(int bytes)? onDeleted, +}) { + AppLog.instance.trace("lib/pages/download_page.dart::_deleteAudioGroup"); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_deleteAudioGroup.closure#1", + ); + + final path = tasks.first.finalPath!; + final key = _audioPathKey(path); + final ids = tasks.map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.closure#1", + ); + return task.id; + }).toSet(); + void validate() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.validate", + ); + + for (final expected in tasks) { + final current = runtime.downloads.task(expected.id); + if (current.state != DownloadState.completed || + current.finalPath != expected.finalPath || + current.accountIdentity != expected.accountIdentity || + current.track.id != expected.track.id) { + throw const XmlyException('download_changed', '下载记录已变化,请重新选择后删除'); + } + } + if (runtime.downloads.tasks.any((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_deleteAudioGroup.closure#1.validate.closure#1", + ); + return task.state == DownloadState.completed && + task.finalPath != null && + _audioPathKey(task.finalPath!) == key && + !ids.contains(task.id); + })) { + throw const XmlyException('shared_audio', '其他下载记录也引用此文件,请一并选择后删除'); + } + } + + validate(); + for (final task in tasks) { + await runtime.player.stopTaskReference(task.id); + } + validate(); + final type = await FileSystemEntity.type(path, followLinks: false); + if (type == FileSystemEntityType.notFound) { + for (final task in tasks) { + await runtime.downloads.markAudioMissing( + task.id, + expectedPath: task.finalPath!, + ); + } + return; + } + if (type != FileSystemEntityType.file) { + throw const XmlyException('audio_changed', '音频路径已不是普通文件,请检查下载目录'); + } + final file = File(path); + final bytes = await file.length(); + validate(); + await file.delete(); + onDeleted?.call(bytes); + for (final task in tasks) { + try { + await runtime.downloads.markAudioDeleted( + task.id, + expectedPath: task.finalPath, + ); + } catch (error, stack) { + if (!AppLog.instance.errorWasRecorded(error)) { + AppLog.instance.write( + AppLogLevel.error, + 'download', + 'Updating deleted audio record failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + } + const replacement = XmlyException( + 'audio_record_update_failed', + '音频文件已删除,但记录更新未完成,请刷新后检查', + ); + AppLog.instance.linkError(replacement, error); + throw replacement; + } + } + }); +} + +Future setAlbumAutoDownload( + BuildContext context, + AutoDownloadService service, + String identity, + String albumId, + String title, +) async { + AppLog.instance.trace("lib/pages/download_page.dart::setAlbumAutoDownload"); + + if (service.enabled(identity, albumId)) { + await service.setEnabled(identity, albumId, confirmed: false); + return; + } + final account = (service.storage.state['accounts'] as Map)[identity]; + final label = account is Map && account['uid'] is String + ? account['uid'] as String + : identity; + final accepted = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1", + ); + return AlertDialog( + scrollable: true, + title: const Text( + '自动下载新声音', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SingleChildScrollView( + child: Text( + '${title.isEmpty ? "此专辑" : title}\n账号 $label\n\n' + '开启后,启动应用或打开专辑时检查更新,只下载开启后新增的声音,不补下已有集数。\n\n' + '始终使用此账号及正常下载规则。奖励内容会逐集预扣整首听时,未来新增声音不再逐次询问;' + '失败或取消不自动退回。余额不足、登录失效或扣时结果未知时停止,不切换账号或重试扣时。\n\n' + '可随时关闭;已加入的任务和扣时记录保留。', + ), + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1.closure#1", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::setAlbumAutoDownload.closure#1.closure#2", + ); + Navigator.pop(context, true); + }, + child: const Text('同意并开启'), + ), + ], + ); + }, + ); + if (accepted == true && context.mounted) + await service.setEnabled(identity, albumId, confirmed: true); +} + +Future confirmDownloadBatch( + BuildContext context, + DownloadBatch batch, +) async { + AppLog.instance.trace("lib/pages/download_page.dart::confirmDownloadBatch"); + + if (batch.items.isEmpty && batch.albumId == null) { + ScaffoldMessenger.of(context) + .showSnackBar(const SnackBar(content: Text('所选声音已在下载列表中'))); + return false; + } + return await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::confirmDownloadBatch.closure#1", + ); + return AlertDialog( + scrollable: true, + title: Text( + batch.albumId == null ? '下载 ${batch.items.length} 集' : '下载整个专辑', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SizedBox( + width: 480, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (batch.albumId != null) ...[ + Text( + '共 ${batch.albumTotalCount ?? "未知"} 集,首批 ${batch.items.length} 集。' + '当前页处理结束后再请求下一页,单集失败不影响其余声音。', + ), + const SizedBox(height: 8), + const Text('后续每页继续按正常规则逐集扣时;已下载声音自动跳过,可随时暂停。'), + const SizedBox(height: 8), + ], + Text( + batch.totalSeconds == 0 + ? '本批预览无需扣除奖励听时' + : '本批预计扣除 ${batch.totalSeconds} 秒(按实际使用的账号逐集扣除)', + ), + if (batch.totalSeconds > 0) ...[ + const SizedBox(height: 8), + const Text('逐集扣除整首时长,下载失败或取消不自动退回。原任务重试不会重复扣时。'), + ], + if (batch.items.isNotEmpty) const SizedBox(height: 12), + if (batch.items.isNotEmpty) + SizedBox( + height: (batch.items.length * 72.0).clamp(72.0, 260.0), + child: AppScrollbar( + child: ListView.builder( + itemCount: batch.items.length, + itemBuilder: (_, index) { + AppLog.instance.trace( + "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#1", + ); + + final item = batch.items[index]; + return ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text( + item.track.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + item.error ?? + '${item.accountIdentity != batch.accountIdentity ? "已切换账号 · " : ""}${item.seconds} 秒', + ), + ); + }, + ), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#2", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::confirmDownloadBatch.closure#1.closure#3", + ); + Navigator.pop(context, true); + }, + child: Text(batch.totalSeconds > 0 ? '确认扣时并下载' : '下载'), + ), + ], + ); + }, + ) == + true; +} + +class DownloadPage extends StatefulWidget { + const DownloadPage({required this.runtime, super.key}); + final AppRuntime runtime; + @override + State createState() { + AppLog.instance.trace( + "lib/pages/download_page.dart::DownloadPage.createState", + ); + return _DownloadPageState(); + } +} + +class _DownloadPageState extends State { + DownloadService get _service { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._service.get", + ); + return widget.runtime.downloads; + } + + AutoDownloadService get _autoDownloads { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._autoDownloads.get", + ); + return widget.runtime.autoDownloads; + } + + String? _error; + String? _availabilityKey; + int _availabilityEpoch = 0; + bool _refreshingAvailability = false; + Map _available = const {}; + final _expandedAlbums = {}; + final _selectedDownloads = {}; + bool _selectingDownloads = false, _deletingAudio = false; + bool _removingTasks = false; + final _selectedTasks = {}; + bool _selectingTasks = false; + String _taskFilter = ''; + + bool get _downloadActionsBlocked { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._downloadActionsBlocked.get', + ); + return _removingTasks || + _deletingAudio || + widget.runtime.closing || + widget.runtime.restoringBackup || + widget.runtime.restoreNeedsReload; + } + + int _deletionDone = 0, _deletionTotal = 0; + final _downloadQuery = TextEditingController(); + Timer? _searchDebounce; + String _downloadFilter = ''; + StreamSubscription? _taskChanges; + + @override + void initState() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.initState", + ); + + super.initState(); + _listen(); + } + + void _listen() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._listen", + ); + + _taskChanges = _service.changes.listen((_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._listen.closure#1", + ); + _tasksChanged(); + }); + widget.runtime.albumCache.addListener(_cacheChanged); + unawaited(_refreshAvailability(_service.tasks)); + } + + void _tasksChanged() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._tasksChanged", + ); + + if (!mounted) return; + final tasks = _service.tasks; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._tasksChanged.closure#1", + ); + + _selectedTasks.retainAll({ + for (final task in tasks) + if (task.state != DownloadState.completed) task.id, + }); + if (_selectedDownloads.isNotEmpty) { + _selectedDownloads.retainAll( + tasks.where(_canSelectAudio).map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._tasksChanged.closure#1.closure#1", + ); + return task.id; + }), + ); + } + }); + if (!_deletingAudio) unawaited(_refreshAvailability(tasks)); + } + + void _cacheChanged() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._cacheChanged", + ); + + _availabilityKey = null; + _tasksChanged(); + } + + @override + void didUpdateWidget(covariant DownloadPage oldWidget) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.didUpdateWidget", + ); + + super.didUpdateWidget(oldWidget); + if (oldWidget.runtime == widget.runtime) return; + unawaited(_taskChanges?.cancel()); + oldWidget.runtime.albumCache.removeListener(_cacheChanged); + _availabilityKey = null; + _available = const {}; + _selectedDownloads.clear(); + _selectingDownloads = false; + _selectedTasks.clear(); + _selectingTasks = false; + _listen(); + } + + @override + void dispose() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.dispose", + ); + + _searchDebounce?.cancel(); + _downloadQuery.dispose(); + unawaited(_taskChanges?.cancel()); + widget.runtime.albumCache.removeListener(_cacheChanged); + super.dispose(); + } + + Future _refreshAvailability(List tasks) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability", + ); + + final key = tasks + .map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability.closure#1", + ); + return '${task.id}:${task.finalPath}:${task.state.name}'; + }) + .join('|'); + if (key == _availabilityKey) return; + _availabilityKey = key; + final epoch = ++_availabilityEpoch; + final paths = { + for (final task in tasks) + if (task.finalPath != null) task.id: task.finalPath!, + }; + final result = {}; + for (final entry in paths.entries) { + try { + result[entry.key] = await File(entry.value).exists(); + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'download', + 'Checking audio availability failed', + error: error, + stackTrace: stack, + promptUser: false, + ); + result[entry.key] = false; + } + } + if (mounted && epoch == _availabilityEpoch && key == _availabilityKey) { + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._refreshAvailability.closure#2", + ); + _available = result; + }); + } + } + + Future _recheckAvailability() async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability", + ); + + if (_refreshingAvailability || _deletingAudio) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability.closure#1", + ); + _refreshingAvailability = true; + }); + try { + _availabilityKey = null; + await _refreshAvailability(_service.tasks); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._recheckAvailability.closure#2", + ); + _refreshingAvailability = false; + }); + } + } + + Future _run( + Future Function() operation, { + bool recoverable = false, + }) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._run", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._run.closure#1", + ); + + if (_downloadActionsBlocked) return; + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#1", + ); + _error = null; + }); + try { + await operation(); + } on XmlyException catch (error, stack) { + _recordDownloadPageError(error, stack); + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#2", + ); + _error = error.message; + }); + } catch (error, stack) { + if (recoverable) { + if (!AppLog.instance.errorWasRecorded(error)) { + AppLog.instance.write( + AppLogLevel.warning, + 'download', + 'Opening download location failed', + error: error, + stackTrace: stack, + promptUser: false, + ); + } + } else { + _recordDownloadPageError(error, stack); + } + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._run.closure#1.closure#3", + ); + _error = '操作未完成,请检查任务列表和文件状态后重试'; + }); + } + }); + } + + Future _retry(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._retry", + ); + + task = _service.task(task.id); + if (task.state == DownloadState.completed) { + await _service.retry(task.id); + if (mounted) await _recheckAvailability(); + return; + } + if (task.state == DownloadState.awaitingDebit && task.needsConfirmation) { + // Drain the worker that reported the changed fee before preparing again. + await widget.runtime.pauseDownload(task.id); + task = _service.task(task.id); + } + if (task.state != DownloadState.failed && + task.state != DownloadState.paused && + task.state != DownloadState.cancelled) + return; + if (task.processingFailed) { + await _service.retry(task.id); + return; + } + if (task.needsConfirmation || !task.userConfirmed) { + final batch = await _service.prepareRetry(task.id); + if (!mounted) return; + await _service.enqueue(batch, confirmed: true); + } else { + await _service.retry(task.id); + } + } + + Future _adjustProcessing(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing", + ); + + final media = task.settings['media'] as Map? ?? const {}; + final download = task.settings['download'] as Map? ?? const {}; + final savedFormat = media['format']; + final savedBitrate = media['bitrateKbps']; + final savedConflict = download['conflict']; + var format = + const {'original', 'mp3', 'm4a', 'm4b', 'flac'}.contains(savedFormat) + ? savedFormat as String + : 'original'; + var bitrate = + savedBitrate is int && + const {32, 64, 96, 128, 192}.contains(savedBitrate) + ? savedBitrate + : 64; + var conflict = const {'skip', 'overwrite', 'number'}.contains(savedConflict) + ? savedConflict as String + : 'skip'; + var currentTools = true; + final accepted = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1", + ); + return StatefulBuilder( + builder: (context, update) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1", + ); + return AlertDialog( + title: const Text( + '调整处理', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SingleChildScrollView( + child: SizedBox( + width: 380, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('仅重跑处理,不重新取流或扣时。'), + DropdownButton( + isExpanded: true, + value: format, + items: const [ + DropdownMenuItem( + value: 'original', + child: Text('原格式'), + ), + DropdownMenuItem(value: 'mp3', child: Text('MP3')), + DropdownMenuItem(value: 'm4a', child: Text('M4A')), + DropdownMenuItem(value: 'm4b', child: Text('M4B')), + DropdownMenuItem(value: 'flac', child: Text('FLAC')), + ], + onChanged: (value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#1", + ); + update(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#1.closure#1", + ); + + format = value!; + }); + }, + ), + if (format != 'original' && format != 'flac') + DropdownButton( + isExpanded: true, + value: bitrate, + items: [ + for (final value in [32, 64, 96, 128, 192]) + DropdownMenuItem( + value: value, + child: Text('$value kbps'), + ), + ], + onChanged: (value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#2", + ); + update(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#2.closure#1", + ); + + bitrate = value!; + }); + }, + ), + DropdownButton( + isExpanded: true, + value: conflict, + items: const [ + DropdownMenuItem( + value: 'skip', + child: Text( + '同名:校验后跳过', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + DropdownMenuItem( + value: 'overwrite', + child: Text( + '同名:新文件完成后替换', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + DropdownMenuItem( + value: 'number', + child: Text( + '同名:自动加编号', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + onChanged: (value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#3", + ); + update(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#3.closure#1", + ); + + conflict = value!; + }); + }, + ), + CheckboxListTile( + contentPadding: EdgeInsets.zero, + value: currentTools, + title: const Text('使用当前工具路径'), + onChanged: (value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#4", + ); + update(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#4.closure#1", + ); + + currentTools = value!; + }); + }, + ), + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#5", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._adjustProcessing.closure#1.closure#1.closure#6", + ); + Navigator.pop(context, true); + }, + child: const Text('保存并重试'), + ), + ], + ); + }, + ); + }, + ); + if (accepted == true) + await _service.reprocess( + task.id, + format: format, + bitrateKbps: bitrate, + conflict: conflict, + useCurrentTools: currentTools, + ); + } + + Future _reacquire(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._reacquire", + ); + + final accepted = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1", + ); + return AlertDialog( + scrollable: true, + title: const Text( + '重新获取音频?', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: Text('${task.track.title}\n清除本任务缓存并重新核验权限,成品和扣时记录会保留。'), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1.closure#1", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._reacquire.closure#1.closure#2", + ); + Navigator.pop(context, true); + }, + child: const Text('重新获取'), + ), + ], + ); + }, + ); + if (accepted != true) return; + await widget.runtime.reacquireDownload(task.id); + } + + Future _relocate(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._relocate", + ); + + final accepted = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1", + ); + return AlertDialog( + scrollable: true, + title: const Text( + '更换目录', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SelectableText( + '${task.track.title}\n${task.rootDirectory}\n旧缓存不自动移动,原扣时记录保留。', + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1.closure#1", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._relocate.closure#1.closure#2", + ); + Navigator.pop(context, true); + }, + child: const Text('选择目录'), + ), + ], + ); + }, + ); + if (accepted != true) return; + final directory = await FilePicker.getDirectoryPath( + dialogTitle: '选择本任务的下载目录', + ); + if (directory == null) return; + await widget.runtime.relocateDownload(task.id, directory); + } + + void _selectTasks(Iterable tasks) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._selectTasks', + ); + if (_downloadActionsBlocked) return; + final ids = {for (final task in tasks) task.id}; + if (ids.isEmpty) return; + setState(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._selectTasks.closure#1', + ); + _selectingTasks = true; + if (ids.every(_selectedTasks.contains)) { + _selectedTasks.removeAll(ids); + } else { + _selectedTasks.addAll(ids); + } + }); + } + + Future _taskBatch(String action) async { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._taskBatch', + ); + if (_downloadActionsBlocked) return; + final selected = [ + for (final task in _service.tasks) + if (_selectedTasks.contains(task.id) && + task.state != DownloadState.completed) + task, + ]; + if (selected.isEmpty) return; + if (action == 'delete') { + await _confirmTaskRemoval(selectedTasks: selected); + return; + } + setState(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#1', + ); + _removingTasks = true; + }); + var succeeded = 0; + final failures = []; + try { + for (final task in selected) { + if (!mounted || + widget.runtime.closing || + widget.runtime.restoringBackup || + widget.runtime.restoreNeedsReload) { + failures.add('操作已停止,请先完成退出或备份恢复'); + break; + } + try { + final current = _service.task(task.id); + if (action == 'pause') { + await widget.runtime.pauseDownload(task.id); + } else { + await _retry(current); + final after = _service.task(task.id); + if (after.state != DownloadState.completed && + (!after.active || + after.state == DownloadState.awaitingDebit && + after.needsConfirmation)) { + failures.add('${task.track.title}:未继续,可能已取消确认'); + continue; + } + } + succeeded++; + _selectedTasks.remove(task.id); + } catch (error, stack) { + _recordDownloadPageError(error, stack); + failures.add( + '${task.track.title}:${error is XmlyException ? error.message : '操作失败'}', + ); + } + } + if (mounted) + setState(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#2', + ); + _error = + '${action == 'pause' ? '暂停' : '继续'}完成 $succeeded / ${selected.length} 个任务' + '${failures.isEmpty ? '' : ';未完成项保留选中:${failures.join(';')}'}'; + }); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._taskBatch.closure#3', + ); + _removingTasks = false; + }); + } + } + + Widget _taskList(List tasks, List completed) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._taskList', + ); + final compact = MediaQuery.sizeOf(context).width < 320; + final visible = tasks.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#1", + ); + return '${task.track.title} ${task.track.album}'.toLowerCase().contains( + _taskFilter, + ); + }).toList(); + final allJobs = _service.albumJobs.where((job) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#2", + ); + return job.state != 'completed' && job.state != 'cancelled'; + }).toList(); + final taskJobs = { + for (final job in allJobs) + for (final id in job.taskIds) id: job.id, + }; + final completedIds = {for (final task in completed) task.id}; + final jobTasks = >{}; + final standalone = []; + for (final task in visible) { + final jobId = taskJobs[task.id]; + if (jobId == null) { + standalone.add(task); + } else { + (jobTasks[jobId] ??= []).add(task); + } + } + final jobs = [ + for (final job in allJobs) + if (job.title.toLowerCase().contains(_taskFilter) || + jobTasks.containsKey(job.id)) + job, + ]; + final hasUnfinished = + tasks.isNotEmpty || + _service.albumJobs.any((job) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#3", + ); + return job.state != 'completed' && job.state != 'cancelled'; + }); + final buttonStyle = OutlinedButton.styleFrom( + minimumSize: const Size(48, 48), + ); + final textStyle = TextButton.styleFrom(minimumSize: const Size(48, 48)); + return LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4", + ); + return Column( + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxHeight: math.max(0, constraints.maxHeight - 48), + ), + child: SingleChildScrollView( + primary: false, + child: Padding( + padding: EdgeInsets.all(compact ? 8 : 12), + child: Column( + children: [ + TextField( + key: const ValueKey('downloadTaskSearch'), + decoration: const InputDecoration( + labelText: '搜索任务', + prefixIcon: Icon(Icons.search), + ), + onChanged: (text) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#1", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#1.closure#1", + ); + _taskFilter = text.trim().toLowerCase(); + }); + }, + ), + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + for (final (label, icon, action) + in < + (String, IconData, Future Function()) + >[ + ( + '全部暂停', + Icons.pause, + widget.runtime.pauseAllDownloads, + ), + ('全部继续', Icons.download, _service.resumeAll), + ( + '全部取消', + Icons.cancel_outlined, + _confirmTaskRemoval, + ), + ]) + OutlinedButton.icon( + style: buttonStyle, + onPressed: + _downloadActionsBlocked || !hasUnfinished + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#2", + ); + _run(action); + }, + icon: Icon(icon), + label: Text(label), + ), + if (!_selectingTasks) + TextButton.icon( + style: textStyle, + onPressed: + _downloadActionsBlocked || visible.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#3", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#3.closure#1", + ); + _selectingTasks = true; + }); + }, + icon: const Icon(Icons.checklist), + label: const Text('选择任务'), + ) + else ...[ + Text('已选 ${_selectedTasks.length} 个任务'), + TextButton( + style: textStyle, + onPressed: + _downloadActionsBlocked || visible.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#4", + ); + _selectTasks(visible); + }, + child: Text( + _taskFilter.isEmpty + ? '全选/取消全选' + : '搜索结果全选/取消全选', + ), + ), + for (final (action, label) in [ + ('pause', '暂停所选'), + ('resume', '继续所选'), + ('delete', '删除所选任务'), + ]) + OutlinedButton( + style: buttonStyle, + onPressed: + _downloadActionsBlocked || + _selectedTasks.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#5", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#5.closure#1", + ); + return _taskBatch(action); + }); + }, + child: Text(label), + ), + TextButton( + style: textStyle, + onPressed: _downloadActionsBlocked + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#6", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#6.closure#1", + ); + _selectingTasks = false; + _selectedTasks.clear(); + }); + }, + child: const Text('取消多选'), + ), + ], + ], + ), + ), + if (_taskFilter.isNotEmpty) + Text('匹配 ${visible.length} / 共 ${tasks.length} 个任务'), + for (final error in [ + if (_error != null) _error!, + ..._autoDownloads.errors, + ]) + Text( + error, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ], + ), + ), + ), + ), + Expanded( + child: AppScrollbar( + child: ListView.builder( + key: const PageStorageKey('compact-download-tasks'), + itemCount: jobs.length + standalone.length, + itemBuilder: (context, index) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskList.closure#4.closure#7", + ); + return index < jobs.length + ? _albumJobCard( + jobs[index], + jobTasks[jobs[index].id] ?? const [], + compact, + jobs[index].taskIds + .where(completedIds.contains) + .length, + ) + : _taskCard(standalone[index - jobs.length], compact); + }, + ), + ), + ), + ], + ); + }, + ); + } + + String _downloadAccountLabel(String identity) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._downloadAccountLabel', + ); + if (identity == 'anonymous') return '不登录(免费内容)'; + final record = + (widget.runtime.storage.state['accounts'] as Map)[identity] as Map?; + final uid = record?['uid']; + return uid == null ? '原账号' : '账号 $uid'; + } + + Future _showAlbumJobDetails(DownloadAlbumJob job) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._showAlbumJobDetails', + ); + return showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._showAlbumJobDetails.closure#1', + ); + return AlertDialog( + scrollable: true, + title: const Text('任务详情'), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(job.title), + const SizedBox(height: 8), + Text(_downloadAccountLabel(job.accountIdentity)), + const SizedBox(height: 8), + SelectableText('目录:${job.rootDirectory}'), + ], + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._showAlbumJobDetails.closure#1.closure#1', + ); + Navigator.pop(context); + }, + child: const Text('关闭'), + ), + ], + ); + }, + ); + } + + Widget _albumJobCard( + DownloadAlbumJob job, + List tasks, + bool compact, + int completed, + ) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard', + ); + final state = switch (job.state) { + 'queued' => '等待下载', + 'running' => '下载中', + 'paused' => '已暂停', + 'failed' => '下载失败', + 'completed' => '已结束', + 'cancelled' => '已取消', + _ => '状态未知', + }; + return ExpansionTile( + key: PageStorageKey('download-album-job:${job.id}'), + minTileHeight: 48, + tilePadding: EdgeInsets.symmetric(horizontal: compact ? 8 : 16), + title: Text(job.title, maxLines: 2, overflow: TextOverflow.ellipsis), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('整专辑 · $state'), + Text( + '本次完成 $completed 集' + '${job.total > 0 ? ' · 专辑共 ${job.total} 集' : ''}', + ), + Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + TextButton.icon( + style: TextButton.styleFrom(minimumSize: const Size(48, 48)), + onPressed: _downloadActionsBlocked + ? null + : () { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#1', + ); + _run(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#1.closure#1', + ); + return job.state == 'running' + ? _service.pauseAlbum(job.id) + : _service.resumeAlbum(job.id); + }); + }, + icon: Icon( + job.state == 'running' ? Icons.pause : Icons.download, + ), + label: Text(job.state == 'running' ? '暂停' : '继续'), + ), + PopupMenuButton( + enabled: !_downloadActionsBlocked, + tooltip: '专辑任务操作', + onSelected: (action) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#2', + ); + _run(() async { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#2.closure#1', + ); + switch (action) { + case 'details': + await _showAlbumJobDetails(job); + case 'refresh': + await _service.refreshAlbum(job.id); + case 'cancel': + await _cancelAlbum(job.id); + } + }); + }, + itemBuilder: (_) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#3', + ); + return [ + const PopupMenuItem(value: 'details', child: Text('任务详情')), + if (job.state != 'running') + const PopupMenuItem( + value: 'refresh', + child: Text('刷新专辑'), + ), + const PopupMenuItem(value: 'cancel', child: Text('取消专辑任务')), + ]; + }, + ), + ], + ), + ], + ), + children: [ + if (job.error != null) + Padding( + padding: EdgeInsets.symmetric(horizontal: compact ? 8 : 16), + child: Text( + job.error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + if (tasks.isNotEmpty) + SizedBox( + height: (tasks.length * 48.0).clamp(48.0, 400.0).toDouble(), + child: ListView.builder( + key: PageStorageKey('download-album-job-tasks:${job.id}'), + primary: false, + itemCount: tasks.length, + itemBuilder: (_, index) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._albumJobCard.closure#4', + ); + return _taskCard(tasks[index], compact); + }, + ), + ), + ], + ); + } + + Future _cancel(DownloadTask task) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._cancel', + ); + return _confirmTaskRemoval(task: task); + } + + Future _confirmTaskRemoval({ + DownloadTask? task, + String? albumId, + List? selectedTasks, + }) async { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval', + ); + if (_downloadActionsBlocked) return; + setState(() { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#1', + ); + _removingTasks = true; + }); + try { + final all = task == null && albumId == null && selectedTasks == null; + final confirmed = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2', + ); + return AlertDialog( + scrollable: true, + title: Text( + task != null + ? '删除此任务?' + : selectedTasks != null + ? '删除选中的 ${selectedTasks.length} 个任务?' + : all + ? '全部取消?' + : '取消整专辑下载?', + ), + content: Text( + task != null + ? '停止并永久删除此任务记录,不能再恢复任务。已下载文件、缓存和扣时记录保留,不自动退款。${task.state == DownloadState.completed ? '此记录也会从“已下载”列表移除,磁盘音频不会删除。' : ''}' + : selectedTasks != null + ? '停止并永久删除选中的任务记录,不能恢复任务。已下载文件、缓存和扣时记录保留,不自动退款。' + : '停止${all ? '所有' : '此专辑的'}后续分页,永久删除${all ? '全部' : '此专辑的'}未完成任务。已完成记录、已下载文件、缓存和扣时记录保留,不自动退款。', + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2.closure#1', + ); + Navigator.pop(context, false); + }, + child: const Text('返回'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#2.closure#2', + ); + Navigator.pop(context, true); + }, + child: Text( + task != null || selectedTasks != null + ? '删除任务' + : all + ? '全部取消' + : '取消专辑任务', + ), + ), + ], + ); + }, + ); + if (confirmed != true || !mounted) return; + if (task != null) { + await widget.runtime.cancelDownload(task.id); + } else if (selectedTasks != null) { + await widget.runtime.cancelDownloads( + selectedTasks.map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#3", + ); + return task.id; + }), + ); + } else if (albumId != null) { + await widget.runtime.cancelAlbumDownloads(albumId); + } else { + await widget.runtime.cancelAllDownloads(); + } + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._confirmTaskRemoval.closure#4", + ); + _removingTasks = false; + }); + } + } + + Future _open(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._open", + ); + + final path = task.finalPath == null + ? task.rootDirectory + : p.dirname(task.finalPath!); + if (!await Directory(path).exists()) + throw const FileSystemException('Directory missing'); + if (Platform.isAndroid) { + if (task.finalPath case final file?) { + await AndroidPlatform.openAudioFile(file); + } else if (mounted) { + await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._open.closure#1", + ); + return AlertDialog( + scrollable: true, + title: const Text( + '下载目录', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + content: SelectableText(path), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._open.closure#1.closure#1", + ); + Navigator.pop(context); + }, + child: const Text('关闭'), + ), + ], + ); + }, + ); + } + return; + } + final executable = Platform.isWindows + ? 'explorer.exe' + : Platform.isMacOS + ? 'open' + : 'xdg-open'; + await Process.start(executable, [path], runInShell: false); + } + + Future _delete(DownloadTask task) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._delete", + ); + + if (_deletingAudio) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._delete.closure#1", + ); + _deletingAudio = true; + }); + try { + if (await deleteDownloadedAudio(context, widget.runtime, task)) { + _availabilityKey = null; + await _refreshAvailability(_service.tasks); + } + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._delete.closure#2", + ); + _deletingAudio = false; + }); + } + } + + bool _canSelectAudio(DownloadTask task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._canSelectAudio", + ); + return task.state == DownloadState.completed && task.finalPath != null; + } + + void _selectAudio(Iterable tasks) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._selectAudio", + ); + + if (_deletingAudio) return; + final ids = tasks.where(_canSelectAudio).map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._selectAudio.closure#1", + ); + return task.id; + }).toSet(); + if (ids.isEmpty) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._selectAudio.closure#2", + ); + + _selectingDownloads = true; + if (ids.every(_selectedDownloads.contains)) { + _selectedDownloads.removeAll(ids); + } else { + _selectedDownloads.addAll(ids); + } + }); + } + + Future _deleteSelectedAudio() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1", + ); + + if (_deletingAudio || _selectedDownloads.isEmpty) return; + final runtime = widget.runtime; + final groups = >{}; + for (final task in _service.tasks.where(_canSelectAudio)) { + if (_selectedDownloads.contains(task.id)) { + groups + .putIfAbsent(_audioPathKey(task.finalPath!), () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#1", + ); + return []; + }) + .add(task); + } + } + if (groups.isEmpty) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#2", + ); + + _deletingAudio = true; + _deletionDone = 0; + _deletionTotal = 0; + }); + try { + var estimatedBytes = 0, unknownSizes = 0; + for (final tasks in groups.values) { + try { + final stat = await File(tasks.first.finalPath!).stat(); + if (stat.type == FileSystemEntityType.file) { + estimatedBytes += stat.size; + } else { + unknownSizes++; + } + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'download', + 'Estimating audio size failed', + error: error, + stackTrace: stack, + promptUser: false, + ); + unknownSizes++; + } + } + if (!mounted || widget.runtime != runtime) return; + final selected = groups.values.fold>([], ( + selected, + tasks, + ) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#3", + ); + selected.addAll(tasks); + return selected; + }); + final count = selected.length; + final hiddenSelected = + count - _matchingDownloads(selected, _downloadFilter).length; + final confirmed = await showDialog( + context: context, + builder: (context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4", + ); + return AlertDialog( + scrollable: true, + title: Text('删除 $count 条声音的音频?'), + content: Text( + '共 ${groups.length} 个路径,预计释放 ${_bytes(estimatedBytes)}' + '${unknownSizes > 0 ? "(另有 $unknownSizes 个路径大小未知或文件已缺失)" : ""}。\n\n' + '${hiddenSelected > 0 ? "其中 $hiddenSelected 条已选声音不在当前搜索结果中,也将删除其音频。\n\n" : ""}' + '正在使用这些文件的播放会停止。任务和扣时记录保留;缺失文件不会记为主动删除。', + ), + actions: [ + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4.closure#1", + ); + Navigator.pop(context, false); + }, + child: const Text('取消'), + ), + FilledButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#4.closure#2", + ); + Navigator.pop(context, true); + }, + child: const Text('删除所选音频'), + ), + ], + ); + }, + ); + if (confirmed != true || !mounted || widget.runtime != runtime) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#5", + ); + _deletionTotal = groups.length; + }); + var freedBytes = 0, deletedFiles = 0; + final failures = []; + final cleared = {}; + for (final tasks in groups.values) { + try { + await _deleteAudioGroup( + runtime, + tasks, + onDeleted: (bytes) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#6", + ); + + freedBytes += bytes; + deletedFiles++; + }, + ); + cleared.addAll( + tasks.map((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#7", + ); + return task.id; + }), + ); + } catch (error, stack) { + _recordDownloadPageError(error, stack); + failures.add( + '${tasks.first.track.title}:${error is XmlyException ? error.message : "删除或记录更新未完成,请刷新后重试"}', + ); + } + if (mounted && widget.runtime == runtime) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#8", + ); + _deletionDone++; + }); + } + if (!mounted || widget.runtime != runtime) return; + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#9", + ); + + _selectedDownloads.removeAll(cleared); + if (_selectedDownloads.isEmpty) _selectingDownloads = false; + _error = failures.isEmpty + ? null + : '${failures.length} 个路径未完全处理;已删除文件不会恢复。\n${failures.take(3).join("\n")}'; + }); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + '已删除 $deletedFiles 个文件,释放 ${_bytes(freedBytes)};${failures.length} 项未完成', + ), + ), + ); + _availabilityKey = null; + await _refreshAvailability(_service.tasks); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._deleteSelectedAudio.closure#1.closure#10", + ); + _deletingAudio = false; + }); + } + }); + } + + Future _openAlbum(String albumId) async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._openAlbum", + ); + + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._openAlbum.closure#1", + ); + return AlbumPageView( + runtime: widget.runtime, + albumId: albumId, + onDownload: (tracks) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._openAlbum.closure#1.closure#1", + ); + return requestDownloads(context, widget.runtime, tracks); + }, + onPlayAlbum: widget.runtime.player.playAlbum, + ); + }, + ), + ); + if (!mounted) return; + _availabilityKey = null; + await _refreshAvailability(_service.tasks); + } + + Widget _albumCard( + String albumId, + List tasks, + bool compact, { + required bool downloaded, + }) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard", + ); + + final cached = albumId.isEmpty ? null : widget.runtime.albumCache[albumId]; + final album = cached?.album; + final total = album?.total ?? 0; + late final completed = { + for (final task in tasks) + if (_available[task.id] == true) task.track.id, + }.length; + final missing = downloaded + ? tasks.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#1", + ); + return task.finalPath == null || _available[task.id] == false; + }).length + : 0; + final states = {}; + for (final task in tasks) { + states.update( + task.state, + (count) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#2", + ); + return count + 1; + }, + ifAbsent: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#3", + ); + return 1; + }, + ); + } + final summary = [ + for (final entry in states.entries) '${_state(entry.key)} ${entry.value}', + if (missing > 0) '文件缺失 $missing', + ].join(' · '); + final title = albumId.isEmpty + ? '未归属专辑的声音' + : album != null && album.title.isNotEmpty + ? album.title + : tasks.first.track.album.isNotEmpty + ? tasks.first.track.album + : '专辑 $albumId'; + final expansionKey = '${downloaded ? 'downloaded' : 'tasks'}:$albumId'; + final expanded = _expandedAlbums.contains(expansionKey); + late final selectable = tasks.where(_canSelectAudio).toList(); + late final selected = selectable.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#4", + ); + return _selectedDownloads.contains(task.id); + }).length; + final selecting = downloaded && _selectingDownloads; + void toggle() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.toggle", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.toggle.closure#1", + ); + + if (expanded) { + _expandedAlbums.remove(expansionKey); + } else { + _expandedAlbums.add(expansionKey); + } + }); + } + + return Card( + margin: EdgeInsets.symmetric(horizontal: compact ? 8 : 16, vertical: 6), + child: Column( + children: [ + ListTile( + contentPadding: EdgeInsets.symmetric( + horizontal: compact ? 8 : 16, + vertical: 6, + ), + leading: selecting + ? Checkbox( + tristate: true, + value: selected == 0 + ? false + : selected == selectable.length + ? true + : null, + onChanged: _deletingAudio || selectable.isEmpty + ? null + : (_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#5", + ); + _selectAudio(selectable); + }, + ) + : compact + ? null + : CoverImage( + uri: album?.coverUrl ?? tasks.first.track.coverUrl, + localPath: cached?.coverPath, + size: 52, + downloaded: downloaded && completed > 0, + ), + title: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (downloaded) + Text( + '$completed / ${total > 0 ? total : "总集数未知"} 集已下载', + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + if (downloaded && total > 0) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: LinearProgressIndicator( + value: (completed / total).clamp(0.0, 1.0), + ), + ), + Text( + summary, + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + ], + ), + onTap: selecting + ? (_deletingAudio + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#6", + ); + _selectAudio(selectable); + }) + : albumId.isEmpty + ? toggle + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#7", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#7.closure#1", + ); + return _openAlbum(albumId); + }); + }, + onLongPress: downloaded && !_deletingAudio + ? () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#8", + ); + _selectAudio(selectable); + } + : null, + trailing: IconButton( + tooltip: expanded ? '收起声音与操作' : '展开声音与操作', + icon: Icon(expanded ? Icons.expand_less : Icons.expand_more), + onPressed: toggle, + ), + ), + if (expanded) ...[ + const Divider(height: 1), + SizedBox( + height: (tasks.length * (downloaded ? 80.0 : 260.0)) + .clamp(80.0, 400.0) + .toDouble(), + child: ListView.builder( + key: PageStorageKey('download-album-tracks:$expansionKey'), + primary: false, + itemCount: tasks.length, + itemBuilder: (_, index) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumCard.closure#9", + ); + return downloaded + ? _downloadedTrack(tasks[index], compact) + : _taskCard(tasks[index], compact); + }, + ), + ), + ], + ], + ), + ); + } + + Widget _downloadedTrack( + DownloadTask task, + bool compact, { + bool searchResult = false, + }) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack", + ); + + final available = _available[task.id] == true; + return ListTile( + selected: _selectingDownloads && _selectedDownloads.contains(task.id), + leading: _selectingDownloads + ? Checkbox( + value: _selectedDownloads.contains(task.id), + onChanged: _deletingAudio || !_canSelectAudio(task) + ? null + : (_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#1", + ); + _selectAudio([task]); + }, + ) + : compact + ? null + : CoverImage( + uri: searchResult ? null : task.track.coverUrl, + localPath: task.track.albumId.isEmpty + ? null + : widget.runtime.albumCache[task.track.albumId]?.coverPath, + downloaded: available, + size: 44, + ), + title: AdaptiveText(task.track.title), + subtitle: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (searchResult) + Text( + _downloadAlbumTitle(task), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + Text( + _available.containsKey(task.id) + ? (available ? '已下载' : '音频文件已不存在') + : '正在检查本地文件', + ), + ], + ), + onLongPress: _deletingAudio + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#2", + ); + _selectAudio([task]); + }, + onTap: _deletingAudio + ? null + : _selectingDownloads + ? () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#3", + ); + _selectAudio([task]); + } + : available + ? () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#4", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#4.closure#1", + ); + return widget.runtime.player.playLocal(task.id); + }); + } + : null, + trailing: PopupMenuButton( + enabled: !_downloadActionsBlocked && !_selectingDownloads, + tooltip: '已下载声音操作', + onSelected: (action) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#5", + ); + _run(() async { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#5.closure#1", + ); + + switch (action) { + case 'play': + await widget.runtime.player.playLocal(task.id); + case 'next': + await widget.runtime.player.playNext(task.track); + case 'retry': + await _retry(task); + case 'open': + await _open(task); + case 'delete': + await _delete(task); + case 'remove': + await _cancel(task); + } + }, recoverable: action == 'open'); + }, + itemBuilder: (_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedTrack.closure#6", + ); + return [ + if (available) + const PopupMenuItem(value: 'play', child: Text('播放')), + if (available) + const PopupMenuItem(value: 'next', child: Text('下一集播放')), + if (_available[task.id] == false) + const PopupMenuItem(value: 'retry', child: Text('重新下载')), + const PopupMenuItem(value: 'open', child: Text('打开目录')), + if (available) + const PopupMenuItem(value: 'delete', child: Text('删除音频')), + const PopupMenuItem(value: 'remove', child: Text('删除任务')), + ]; + }, + ), + ); + } + + Future _cancelAlbum(String id) { + AppLog.instance.trace( + 'lib/pages/download_page.dart::_DownloadPageState._cancelAlbum', + ); + return _confirmTaskRemoval(albumId: id); + } + + String _downloadAlbumTitle(DownloadTask task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadAlbumTitle", + ); + + final id = task.track.albumId; + final cached = id.isEmpty + ? null + : widget.runtime.albumCache[id]?.album.title; + if (cached != null && cached.isNotEmpty) return cached; + if (task.track.album.isNotEmpty) return task.track.album; + return id.isEmpty ? '未归属专辑的声音' : '专辑 $id'; + } + + void _searchDownloads(String text, {bool immediately = false}) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._searchDownloads", + ); + + _searchDebounce?.cancel(); + void apply() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._searchDownloads.apply", + ); + + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._searchDownloads.apply.closure#1", + ); + _downloadFilter = text.trim().toLowerCase(); + }); + } + + if (immediately) { + apply(); + } else { + _searchDebounce = Timer(const Duration(milliseconds: 180), apply); + } + } + + List _matchingDownloads( + List tasks, + String query, + ) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads", + ); + if (query.isEmpty) return tasks; + final tokens = query.split(RegExp(r'\s+')).where((value) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads.closure#1", + ); + return value.isNotEmpty; + }); + return tasks.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._matchingDownloads.closure#2", + ); + final track = task.track; + final text = [ + _downloadAlbumTitle(task), + track.album, + track.title, + for (final ordinal in { + track.officialPosition, + track.orderNo, + track.episode, + }.whereType()) + '$ordinal 第${ordinal}集', + ].join(' ').toLowerCase(); + return tokens.every(text.contains); + }).toList(); + } + + Widget _downloadedLibrary(List completed) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary", + ); + + final compact = MediaQuery.sizeOf(context).width < 320; + final query = _downloadFilter; + final visible = _matchingDownloads(completed, query); + final hiddenSelected = query.isEmpty || _selectedDownloads.isEmpty + ? 0 + : _selectedDownloads.length - + visible.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#1", + ); + return _selectedDownloads.contains(task.id); + }).length; + return LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2", + ); + return Column( + children: [ + ConstrainedBox( + constraints: BoxConstraints( + maxHeight: math.max(0, constraints.maxHeight - 96), + ), + child: SingleChildScrollView( + primary: false, + child: Column( + children: [ + Padding( + padding: EdgeInsets.fromLTRB( + compact ? 8 : 16, + 12, + compact ? 8 : 16, + 8, + ), + child: TextField( + key: const ValueKey('downloadLibrarySearch'), + controller: _downloadQuery, + decoration: InputDecoration( + labelText: '搜索已下载', + hintText: '专辑、单集标题或集号', + prefixIcon: const Icon(Icons.search), + suffixIcon: ValueListenableBuilder( + valueListenable: _downloadQuery, + builder: (context, value, _) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#1", + ); + return value.text.isEmpty + ? const SizedBox.shrink() + : IconButton( + tooltip: '清除本地搜索', + icon: const Icon(Icons.clear), + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#1.closure#1", + ); + _downloadQuery.clear(); + _searchDownloads('', immediately: true); + }, + ); + }, + ), + ), + textInputAction: TextInputAction.search, + onChanged: _searchDownloads, + onSubmitted: (text) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#2", + ); + _searchDownloads(text, immediately: true); + }, + ), + ), + Wrap( + spacing: 8, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + OutlinedButton.icon( + onPressed: + _refreshingAvailability || + _deletingAudio || + completed.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#3", + ); + _run(_recheckAvailability); + }, + icon: _refreshingAvailability + ? const SizedBox.square( + dimension: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + ), + ) + : const Icon(Icons.refresh), + label: Text( + _refreshingAvailability ? '正在检查' : '刷新本地文件', + ), + ), + if (!_selectingDownloads) + OutlinedButton.icon( + onPressed: _deletingAudio || visible.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#4", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#4.closure#1", + ); + _selectingDownloads = true; + }); + }, + icon: const Icon(Icons.checklist), + label: const Text('多选音频'), + ) + else ...[ + Text( + '已选 ${_selectedDownloads.length} 条' + '${hiddenSelected > 0 ? "(含 $hiddenSelected 条未显示)" : ""}', + ), + TextButton( + onPressed: _deletingAudio || visible.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#5", + ); + _selectAudio(visible); + }, + child: Text( + query.isEmpty ? '全选/取消全选' : '搜索结果全选/取消全选', + ), + ), + FilledButton.icon( + onPressed: + _deletingAudio || _selectedDownloads.isEmpty + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#6", + ); + _run(_deleteSelectedAudio); + }, + icon: const Icon(Icons.delete_outline), + label: const Text('删除所选音频'), + ), + TextButton( + onPressed: _deletingAudio + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#7", + ); + setState(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#7.closure#1", + ); + _selectingDownloads = false; + _selectedDownloads.clear(); + }); + }, + child: const Text('取消多选'), + ), + ], + ], + ), + if (_deletingAudio) ...[ + LinearProgressIndicator( + value: _deletionTotal == 0 + ? null + : _deletionDone / _deletionTotal, + ), + Text( + _deletionTotal == 0 + ? '正在准备删除' + : '正在处理 $_deletionDone / $_deletionTotal 个路径', + ), + ], + if (query.isNotEmpty) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: Text( + '本地下载记录:匹配 ${visible.length} / 共 ${completed.length} 条', + ), + ), + if (query.isNotEmpty && _error != null) + Padding( + padding: const EdgeInsets.all(8), + child: Text( + _error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + ], + ), + ), + ), + Expanded( + child: query.isEmpty + ? _albumList(completed, downloaded: true) + : visible.isEmpty + ? const Center(child: Text('未找到匹配的本地下载记录')) + : AppScrollbar( + child: ListView.builder( + key: ValueKey('downloadSearch:$query'), + itemCount: visible.length, + itemBuilder: (context, index) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._downloadedLibrary.closure#2.closure#8", + ); + return _downloadedTrack( + visible[index], + compact, + searchResult: true, + ); + }, + ), + ), + ), + ], + ); + }, + ); + } + + Widget _albumList(Iterable tasks, {required bool downloaded}) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumList", + ); + + final compact = MediaQuery.sizeOf(context).width < 320; + final groups = >{}; + for (final task in tasks) { + groups + .putIfAbsent(task.track.albumId, () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#1", + ); + return []; + }) + .add(task); + } + if (downloaded) { + for (final group in groups.entries) { + if (group.key.isEmpty) continue; + final originalOrder = { + for (var index = 0; index < group.value.length; index++) + group.value[index].id: index, + }; + int? position(DownloadTask task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumList.position", + ); + return task.track.officialPosition ?? + xmlyPositive(task.track.orderNo) ?? + xmlyPositive(task.track.episode); + } + + group.value.sort((a, b) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#2", + ); + + final left = position(a), right = position(b); + if (left != null && right != null && left != right) { + return left.compareTo(right); + } + if ((left == null) != (right == null)) return left == null ? 1 : -1; + return originalOrder[a.id]!.compareTo(originalOrder[b.id]!); + }); + } + } + final albums = groups.entries.toList(); + return AppScrollbar( + child: ListView.builder( + key: PageStorageKey( + downloaded ? 'downloaded-albums' : 'download-tasks', + ), + itemCount: albums.length + 1, + itemBuilder: (context, index) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._albumList.closure#3", + ); + + if (index > 0) { + final group = albums[index - 1]; + return _albumCard( + group.key, + group.value, + compact, + downloaded: downloaded, + ); + } + return Padding( + padding: EdgeInsets.all(compact ? 8 : 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (final error in [if (_error != null) _error!]) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + error, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + if (albums.isEmpty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 24), + child: Center( + child: Text(downloaded ? '暂无已下载内容' : '暂无下载任务'), + ), + ), + ], + ), + ); + }, + ), + ); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.build", + ); + return StreamBuilder( + stream: _autoDownloads.changes, + builder: (context, _) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.build.closure#1", + ); + + final tasks = _service.tasks; + final completed = tasks.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.build.closure#1.closure#1", + ); + return task.state == DownloadState.completed; + }).toList(); + return DefaultTabController( + length: 2, + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 720), + child: Column( + children: [ + const TabBar( + tabs: [ + Tab(text: '下载任务'), + Tab(text: '已下载'), + ], + ), + Expanded( + child: TabBarView( + children: [ + _taskList( + tasks.where((task) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState.build.closure#1.closure#2", + ); + return task.state != DownloadState.completed; + }).toList(), + completed, + ), + _downloadedLibrary(completed), + ], + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + Widget _taskCard(DownloadTask task, bool compact) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard", + ); + + final total = task.totalBytes; + final progress = total == null || total <= 0 + ? null + : (task.receivedBytes / total).clamp(0.0, 1.0); + final remaining = total == null || task.bytesPerSecond <= 0 + ? null + : ((total - task.receivedBytes).clamp(0, total) / task.bytesPerSecond) + .ceil(); + return ExpansionTile( + key: PageStorageKey('download-task:${task.id}'), + minTileHeight: 48, + tilePadding: EdgeInsets.symmetric(horizontal: compact ? 8 : 16), + childrenPadding: EdgeInsets.fromLTRB( + compact ? 8 : 16, + 0, + compact ? 8 : 16, + 12, + ), + leading: _selectingTasks + ? Checkbox( + value: _selectedTasks.contains(task.id), + onChanged: _downloadActionsBlocked + ? null + : (_) { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#1", + ); + _selectTasks([task]); + }, + ) + : null, + title: Text( + task.track.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + children: [ + Text( + '${task.track.album} · ${_state(task.state)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + AdaptiveText(_downloadAccountLabel(task.accountIdentity)), + AdaptiveText('目录:${task.finalPath ?? task.rootDirectory}'), + if (task.error != null) + Text( + task.error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + if (task.state == DownloadState.downloading || + task.state == DownloadState.processing) ...[ + const SizedBox(height: 12), + LinearProgressIndicator( + value: task.state == DownloadState.processing ? null : progress, + ), + ], + const SizedBox(height: 8), + AdaptiveText( + '${_bytes(task.receivedBytes)} / ${total == null ? "未知" : _bytes(total)} · ${_bytes(task.bytesPerSecond.round())}/s${remaining == null ? "" : " · 剩余 ${remaining}s"}', + ), + if (task.retryAt != null) + AdaptiveText( + '下次重试 ${task.retryAt!.toLocal().toString().split(".").first}', + ), + if (task.actualQuality != null) + AdaptiveText('实际音质:${task.actualQuality}'), + if (task.warning != null) + Text( + task.warning!, + style: TextStyle(color: Theme.of(context).colorScheme.tertiary), + ), + Wrap( + alignment: WrapAlignment.center, + spacing: 8, + runSpacing: 8, + children: [ + if (task.state == DownloadState.awaitingDebit && + task.needsConfirmation) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#2", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#2.closure#1", + ); + return _retry(task); + }); + }, + child: const Text('重新获取'), + ), + if (task.active && + !(task.state == DownloadState.awaitingDebit && + task.needsConfirmation)) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#3", + ); + + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#3.closure#1", + ); + return widget.runtime.pauseDownload(task.id); + }); + }, + child: const Text('暂停'), + ), + if (task.state == DownloadState.paused) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#4", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#4.closure#1", + ); + return _retry(task); + }); + }, + child: Text( + task.needsConfirmation && !task.processingFailed + ? '重新获取' + : '继续', + ), + ), + if (task.state == DownloadState.failed) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#5", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#5.closure#1", + ); + return _retry(task); + }); + }, + child: Text( + task.needsConfirmation + ? '重新获取' + : task.processingFailed + ? '重试处理' + : '重试', + ), + ), + if (task.state == DownloadState.cancelled) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#6", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#6.closure#1", + ); + return _retry(task); + }); + }, + child: Text(task.processingFailed ? '恢复并重试处理' : '恢复任务'), + ), + if (task.processingFailed && + (task.state == DownloadState.failed || + task.state == DownloadState.paused || + task.state == DownloadState.cancelled)) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#7", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#7.closure#1", + ); + return _reacquire(task); + }); + }, + child: const Text('重新获取音频'), + ), + if (task.processingFailed && + (task.state == DownloadState.failed || + task.state == DownloadState.paused || + task.state == DownloadState.cancelled)) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#8", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#8.closure#1", + ); + return _adjustProcessing(task); + }); + }, + child: const Text('调整处理'), + ), + TextButton( + onPressed: _downloadActionsBlocked + ? null + : () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#9", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#9.closure#1", + ); + return _cancel(task); + }); + }, + child: const Text('删除任务'), + ), + if (!task.active && task.state != DownloadState.completed) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#10", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#10.closure#1", + ); + return _relocate(task); + }); + }, + child: const Text('更换目录'), + ), + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#11", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#11.closure#1", + ); + return _open(task); + }, recoverable: true); + }, + child: const Text('打开目录'), + ), + if (task.finalPath != null) + TextButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#12", + ); + _run(() { + AppLog.instance.trace( + "lib/pages/download_page.dart::_DownloadPageState._taskCard.closure#12.closure#1", + ); + return _delete(task); + }); + }, + child: const Text('删除音频'), + ), + ], + ), + ], + ); + } +} + +String _bytes(int value) { + AppLog.instance.trace("lib/pages/download_page.dart::_bytes"); + return value < 1024 + ? '${value}B' + : value < 1024 * 1024 + ? '${(value / 1024).toStringAsFixed(1)}KiB' + : '${(value / (1024 * 1024)).toStringAsFixed(1)}MiB'; +} + +String _state(DownloadState state) { + AppLog.instance.trace("lib/pages/download_page.dart::_state"); + return switch (state) { + DownloadState.queued => '等待中', + DownloadState.awaitingDebit => '等待扣时确认', + DownloadState.downloading => '下载中', + DownloadState.paused => '已暂停', + DownloadState.processing => '处理中', + DownloadState.completed => '已完成', + DownloadState.failed => '失败', + DownloadState.cancelled => '已取消', + }; +} diff --git a/lib/pages/player_panel.dart b/lib/pages/player_panel.dart index 1deceb5..01a5dbb 100644 --- a/lib/pages/player_panel.dart +++ b/lib/pages/player_panel.dart @@ -1,2715 +1,2967 @@ -import 'dart:async'; -import 'dart:math' as math; - -import 'package:flutter/gestures.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; - -import '../api/xmly_client.dart'; -import '../api/xmly_experience.dart'; -import '../common/widgets/adaptive_text.dart'; -import '../common/widgets/app_header.dart'; -import '../common/widgets/app_tab_button.dart'; -import '../common/widgets/confirmation_dialog.dart'; -import '../common/widgets/logged_network_image.dart'; -import '../common/widgets/local_panel.dart'; -import '../common/widgets/playback_action_button.dart'; -import '../models/xmly_models.dart'; -import '../services/app_log.dart'; -import '../services/app_runtime.dart'; -import 'anchor_page.dart'; -import 'catalogue_page.dart'; -import 'manuscript_reader.dart'; -import 'playback_mode_control.dart'; -import 'playback_settings_page.dart'; -import 'playback_skip_control.dart'; -import 'playback_speed_control.dart'; -import 'player_queue_panel.dart'; -import 'playback_volume_control.dart'; -import 'track_comments_panel.dart'; - -void _recordPlayerPanelError( - String operation, - Object error, - StackTrace stack, { - bool recoverable = false, -}) { - AppLog.instance.trace("lib/pages/player_panel.dart::_recordPlayerPanelError"); - - final log = AppLog.instance; - if (log.errorWasRecorded(error)) return; - final expected = - error is XmlyException && - const { - 'client_closed', - 'request_cancelled', - 'cancelled', - 'download_stopped', - 'stopped', - 'closed', - 'login_required', - 'login_expired', - 'auth_required', - 'account_changed', - 'account_mismatch', - 'missing_account', - 'confirmation_required', - 'confirmation_changed', - 'insufficient_quota', - 'usage_uncertain', - 'rate_limited', - 'queue_full', - 'catalogue_limit', - 'invalid_page', - }.contains(error.code); - log.write( - recoverable || expected ? AppLogLevel.warning : AppLogLevel.error, - 'player_panel', - operation, - error: error, - stackTrace: stack, - promptUser: !recoverable && !expected, - ); -} - -String playbackTime(double seconds) { - AppLog.instance.trace("lib/pages/player_panel.dart::playbackTime"); - - final total = seconds.isFinite && seconds > 0 ? seconds.floor() : 0; - final hours = total ~/ 3600; - final minutes = (total ~/ 60) % 60; - final rest = (total % 60).toString().padLeft(2, '0'); - return hours > 0 - ? '$hours:${minutes.toString().padLeft(2, '0')}:$rest' - : '$minutes:$rest'; -} - -class PlayerPanel extends StatefulWidget { - const PlayerPanel({ - required this.runtime, - this.expanded = false, - this.miniWindow = false, - this.onExpand, - this.navigatorKey, - super.key, - }); - static const routeName = '/player'; - final AppRuntime runtime; - final bool expanded; - final bool miniWindow; - final VoidCallback? onExpand; - final GlobalKey? navigatorKey; - - @override - State createState() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::PlayerPanel.createState", - ); - return _PlayerPanelState(); - } -} - -class _PlayerPanelState extends State { - PageController _pages = PageController(keepPage: false); - final _retiredPages = {}; - int _paneCount = 1, _secondaryPage = 1; - (int, bool)? _pendingPaneLayout; - bool _configuredManuscript = true; - bool _changingPaneLayout = false; - final _visitedPages = {0}; - int _selectedPage = 0; - final _keyboardFocus = FocusNode( - debugLabel: 'Player shortcuts', - skipTraversal: true, - ); - bool _busy = false, _cancelling = false; - double? _dragPosition; - int? _dragEpoch; - String? _error; - XmlyClient? _favoriteClient; - String? _favoriteKey, _favoriteTrackId, _favoriteError; - bool? _favorite; - bool _favoriteBusy = false, _favoriteMutating = false; - int _favoriteRequest = 0, _libraryRevision = -1; - XmlyClient? _likeClient; - String? _likeKey, _likeTrackId, _likeError, _likeCountError; - int? _likeCount, _favoriteCount; - bool _liked = false, _likeBusy = false, _likeCountLoading = false; - int _likeRequest = 0, _likeCountRequest = 0; - XmlyClient? _manuscriptClient; - String? _manuscriptKey, _manuscriptTrackId, _manuscript, _manuscriptError; - bool _manuscriptLoading = false; - bool _manuscriptLoaded = false; - int _manuscriptRequest = 0; - Completer? _manuscriptCancelled; - Album? _creatorAlbum; - String? _creatorTrackId, _creatorAlbumId, _creatorResolvedAlbumId; - int _creatorRequest = 0; - Completer? _creatorCancelled; - AppRuntime get _runtime { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._runtime.get", - ); - return widget.runtime; - } - - NavigatorState get _navigator { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._navigator.get", - ); - return widget.navigatorKey?.currentState ?? Navigator.of(context); - } - - @override - void initState() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.initState", - ); - - super.initState(); - _runtime.addListener(_favoriteContextChanged); - _runtime.addListener(_likeContextChanged); - _runtime.addListener(_manuscriptContextChanged); - _runtime.addListener(_creatorContextChanged); - if (widget.expanded) { - unawaited(_refreshFavorite()); - _refreshLikes(); - unawaited(_refreshManuscript()); - unawaited(_refreshCreator()); - } - } - - @override - void didUpdateWidget(covariant PlayerPanel oldWidget) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.didUpdateWidget", - ); - - super.didUpdateWidget(oldWidget); - if (oldWidget.runtime != _runtime) { - oldWidget.runtime.removeListener(_favoriteContextChanged); - oldWidget.runtime.removeListener(_likeContextChanged); - oldWidget.runtime.removeListener(_manuscriptContextChanged); - oldWidget.runtime.removeListener(_creatorContextChanged); - _runtime.addListener(_manuscriptContextChanged); - _runtime.addListener(_favoriteContextChanged); - _runtime.addListener(_likeContextChanged); - _runtime.addListener(_creatorContextChanged); - _dragPosition = null; - _dragEpoch = null; - } - if (widget.expanded && - (oldWidget.runtime != _runtime || !oldWidget.expanded)) { - unawaited(_refreshFavorite()); - _refreshLikes(); - } - if (oldWidget.runtime != _runtime && !widget.expanded) _refreshLikes(); - if (oldWidget.runtime != _runtime || - oldWidget.expanded != widget.expanded) { - unawaited(_refreshManuscript()); - unawaited(_refreshCreator()); - } - } - - @override - void dispose() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.dispose", - ); - - _runtime.removeListener(_favoriteContextChanged); - _runtime.removeListener(_likeContextChanged); - _runtime.removeListener(_manuscriptContextChanged); - _runtime.removeListener(_creatorContextChanged); - _creatorRequest++; - _creatorCancelled?.complete(); - _creatorCancelled = null; - _manuscriptRequest++; - _manuscriptCancelled?.complete(); - _manuscriptCancelled = null; - _favoriteRequest++; - _likeRequest++; - _likeCountRequest++; - _pages.dispose(); - for (final controller in _retiredPages) { - controller.dispose(); - } - _retiredPages.clear(); - _keyboardFocus.dispose(); - super.dispose(); - } - - bool get _desktopKeyboard { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._desktopKeyboard.get", - ); - return switch (Theme.of(context).platform) { - TargetPlatform.windows || - TargetPlatform.macOS || - TargetPlatform.linux => true, - _ => false, - }; - } - - String _keyHint(String label, String key) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._keyHint", - ); - return _desktopKeyboard ? '$label($key)' : label; - } - - KeyEventResult _onPlayerKey(FocusNode node, KeyEvent event) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._onPlayerKey", - ); - - // Descendant controls keep their own activation, editing and navigation. - // Also exclude routes above this player, including non-focusing dialogs. - if (!node.hasPrimaryFocus || ModalRoute.of(context)?.isCurrent == false) { - return KeyEventResult.ignored; - } - final keyboard = HardwareKeyboard.instance; - if (keyboard.isControlPressed || - keyboard.isAltPressed || - keyboard.isMetaPressed || - keyboard.isShiftPressed) { - return KeyEventResult.ignored; - } - if (widget.expanded && _paneCount == 1 && _selectedPage != 0) { - return KeyEventResult.ignored; - } - final player = _runtime.player; - if (player.current == null) return KeyEventResult.ignored; - final command = switch (event.logicalKey) { - LogicalKeyboardKey.space => _playPause, - LogicalKeyboardKey.arrowLeft => player.seekBackward, - LogicalKeyboardKey.arrowRight => player.seekForward, - _ => null, - }; - if (command == null) return KeyEventResult.ignored; - // One command per press; repeats must not toggle or enqueue more seeks. - if (event is KeyDownEvent) { - unawaited( - event.logicalKey == LogicalKeyboardKey.space - ? _playPause() - : _act(command), - ); - } - return KeyEventResult.handled; - } - - Widget _withKeyboard(Widget child) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._withKeyboard", - ); - return !_desktopKeyboard - ? child - : Focus( - focusNode: _keyboardFocus, - autofocus: true, - onKeyEvent: _onPlayerKey, - child: GestureDetector( - behavior: HitTestBehavior.translucent, - onTap: _keyboardFocus.requestFocus, - child: child, - ), - ); - } - - void _creatorContextChanged() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._creatorContextChanged', - ); - if (!mounted || !widget.expanded) return; - final track = _runtime.player.current; - if (track?.id != _creatorTrackId || track?.albumId != _creatorAlbumId) { - unawaited(_refreshCreator()); - return; - } - final cached = track == null || track.albumId.isEmpty - ? null - : _runtime.albumCache[track.albumId]?.album; - if (cached?.anchorUid != null && !identical(cached, _creatorAlbum)) { - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._creatorContextChanged.closure#1', - ); - _creatorAlbum = cached; - }); - } - } - - Future _refreshCreator() async { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator', - ); - final runtime = _runtime; - final track = runtime.player.current; - final trackId = track?.id, albumId = track?.albumId; - final request = ++_creatorRequest; - _creatorCancelled?.complete(); - _creatorCancelled = null; - _creatorTrackId = trackId; - _creatorAlbumId = albumId; - final cached = albumId == null || albumId.isEmpty - ? null - : runtime.albumCache[albumId]?.album; - final previous = _creatorAlbum?.id == albumId ? _creatorAlbum : null; - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#1', - ); - _creatorAlbum = cached?.anchorUid != null ? cached : previous ?? cached; - }); - if (!widget.expanded || - trackId == null || - albumId == null || - albumId.isEmpty || - _creatorAlbum?.anchorUid != null || - (previous != null && _creatorResolvedAlbumId == albumId)) { - return; - } - final cancelled = _creatorCancelled = Completer(); - bool current() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.current', - ); - return mounted && - widget.expanded && - identical(runtime, _runtime) && - request == _creatorRequest && - runtime.player.current?.id == trackId && - runtime.player.current?.albumId == albumId; - } - - try { - final page = await runtime.anonymous.withReadPolicy( - () { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#2', - ); - return runtime.anonymous.album(albumId, pageSize: 1); - }, - rateLimitRetries: 0, - cancelled: cancelled.future, - ); - if (current() && page.album.id == albumId) { - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#3', - ); - _creatorAlbum = page.album; - _creatorResolvedAlbumId = albumId; - }); - } - } catch (error, stack) { - if (current()) { - _recordPlayerPanelError( - 'Player creator load failed', - error, - stack, - recoverable: true, - ); - } - } finally { - if (current()) _creatorCancelled = null; - } - } - - void _manuscriptContextChanged() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._manuscriptContextChanged", - ); - - if (!mounted || !widget.expanded) return; - final client = _runtime.player.currentClient; - if (!identical(client, _manuscriptClient) || - client.cacheIdentity != _manuscriptKey || - _runtime.player.current?.id != _manuscriptTrackId) { - unawaited(_refreshManuscript()); - } - } - - Future _refreshManuscript({bool force = false}) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1", - ); - - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - final trackId = _runtime.player.current?.id; - if (!force && - widget.expanded && - identical(client, _manuscriptClient) && - key == _manuscriptKey && - trackId == _manuscriptTrackId && - (_manuscriptLoaded || _manuscriptLoading)) { - return; - } - final request = ++_manuscriptRequest; - _manuscriptCancelled?.complete(); - _manuscriptCancelled = null; - _manuscriptClient = client; - _manuscriptKey = key; - _manuscriptTrackId = trackId; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#1", - ); - - _manuscript = null; - _manuscriptError = null; - _manuscriptLoaded = false; - _manuscriptLoading = widget.expanded && trackId != null; - }); - if (!_manuscriptLoading) return; - final cancelled = _manuscriptCancelled = Completer(); - bool current() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.current", - ); - return mounted && - widget.expanded && - request == _manuscriptRequest && - identical(client, _runtime.player.currentClient) && - key == _runtime.player.currentClient.cacheIdentity && - trackId == _runtime.player.current?.id; - } - - try { - final manuscript = await client.withReadPolicy( - () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#2", - ); - return client.fetchManuscript(trackId!); - }, - rateLimitRetries: 0, - cancelled: cancelled.future, - ); - if (current()) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#3", - ); - - _manuscript = manuscript; - _manuscriptLoaded = true; - if (manuscript == null) { - if (_selectedPage == 1) _selectedPage = 2; - if (_secondaryPage == 1) _secondaryPage = 2; - if (_paneCount == 2 || _selectedPage == 2) { - _visitedPages.add(2); - } - } - }); - } - } catch (error, stack) { - _recordPlayerPanelError('Manuscript load failed', error, stack); - if (current()) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#4", - ); - _manuscriptError = error is XmlyException - ? error.message - : '文稿读取失败,请重试'; - }); - } - } finally { - if (current()) { - _manuscriptCancelled = null; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#5", - ); - _manuscriptLoading = false; - }); - } - } - }); - } - - void _selectPage(int page) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._selectPage', - ); - if (!_pageOrder.contains(page)) return; - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._selectPage.closure#1', - ); - _selectedPage = page; - if (page != 0) _secondaryPage = page; - _visitedPages.add(page); - }); - if (_paneCount == 1 && _pages.hasClients && !_changingPaneLayout) { - unawaited( - _pages.animateToPage( - _pageOrder.indexOf(page), - duration: MediaQuery.disableAnimationsOf(context) - ? Duration.zero - : const Duration(milliseconds: 250), - curve: Curves.easeOutCubic, - ), - ); - } - } - - bool get _hasManuscript { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._hasManuscript.get', - ); - return !_manuscriptLoaded || _manuscript != null; - } - - List get _pageOrder { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._pageOrder.get', - ); - final secondary = [if (_hasManuscript) 1, 2, 3]; - return [ - 0, - if (_paneCount == 2) _secondaryPage, - for (final page in secondary) - if (_paneCount == 1 || page != _secondaryPage) page, - ]; - } - - void _configurePanes(int count) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes', - ); - final layout = (count, _hasManuscript); - if (count == _paneCount && _hasManuscript == _configuredManuscript) { - _pendingPaneLayout = null; - return; - } - if (layout == _pendingPaneLayout) return; - _pendingPaneLayout = layout; - WidgetsBinding.instance.addPostFrameCallback((_) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1', - ); - if (!mounted || _pendingPaneLayout != layout) return; - _pendingPaneLayout = null; - final oldPages = _pages; - _changingPaneLayout = true; - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1.closure#1', - ); - _paneCount = count; - _configuredManuscript = _hasManuscript; - _pages = PageController( - keepPage: false, - viewportFraction: 1 / count, - initialPage: count == 1 ? _pageOrder.indexOf(_selectedPage) : 0, - ); - if (count == 2) _visitedPages.add(_secondaryPage); - }); - final installedPages = _pages; - _retiredPages.add(oldPages); - WidgetsBinding.instance.addPostFrameCallback((_) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1.closure#2', - ); - if (mounted && identical(_pages, installedPages)) { - if (installedPages.hasClients) { - installedPages.jumpToPage( - count == 1 ? _pageOrder.indexOf(_selectedPage) : 0, - ); - } - _changingPaneLayout = false; - } - if (_retiredPages.remove(oldPages)) oldPages.dispose(); - }); - }); - } - - void _pageSwiped(int index) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._pageSwiped', - ); - if (_paneCount != 1 || _changingPaneLayout) return; - final order = _pageOrder; - if (index >= order.length) return; - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._pageSwiped.closure#1', - ); - _selectedPage = order[index]; - if (_selectedPage != 0) _secondaryPage = _selectedPage; - _visitedPages.add(_selectedPage); - }); - } - - Widget _manuscriptPage(Track? track) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._manuscriptPage', - ); - if (track == null) return const Center(child: Text('尚未选择声音')); - if (_manuscriptLoading) { - return const Center(child: CircularProgressIndicator()); - } - if (_manuscriptError != null) { - return Center( - child: SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Text(_manuscriptError!, textAlign: TextAlign.center), - PlaybackActionButton( - onPressed: () { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._manuscriptPage.closure#1', - ); - unawaited(_refreshManuscript(force: true)); - }, - icon: const Icon(Icons.refresh), - label: '重试文稿', - ), - ], - ), - ), - ); - } - if (_manuscript == null) { - return const Center(child: Text('此声音暂无文稿')); - } - return Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 900), - child: ManuscriptReader( - key: ValueKey(( - _manuscriptClient, - _manuscriptKey, - _manuscriptTrackId, - )), - manuscript: _manuscript!, - showTitle: false, - ), - ), - ); - } - - void _favoriteContextChanged() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteContextChanged", - ); - - if (!widget.expanded || !mounted) return; - final client = _runtime.player.currentClient; - final changed = - !identical(client, _favoriteClient) || - client.cacheIdentity != _favoriteKey || - _runtime.player.current?.id != _favoriteTrackId; - final revised = _libraryRevision != _runtime.libraryRevision; - _libraryRevision = _runtime.libraryRevision; - if (changed || (revised && !_favoriteMutating)) { - unawaited(_refreshFavorite()); - final track = _runtime.player.current; - if (!changed && track != null) { - unawaited(_refreshLikeCount(track, force: true)); - } - } - } - - bool _favoriteCurrent( - XmlyClient client, - String key, - String trackId, - int request, - ) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteCurrent", - ); - return mounted && - request == _favoriteRequest && - identical(client, _runtime.player.currentClient) && - key == _runtime.player.currentClient.cacheIdentity && - trackId == _runtime.player.current?.id; - } - - void _likeContextChanged() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeContextChanged", - ); - if (!mounted) return; - final client = _runtime.player.currentClient; - if (!identical(client, _likeClient) || - client.cacheIdentity != _likeKey || - _runtime.player.current?.id != _likeTrackId) { - _refreshLikes(); - } - } - - bool _likeContextCurrent(XmlyClient client, String key, String trackId) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeContextCurrent", - ); - return mounted && - identical(client, _runtime.player.currentClient) && - key == _runtime.player.currentClient.cacheIdentity && - trackId == _runtime.player.current?.id; - } - - bool _likeCurrent( - XmlyClient client, - String key, - String trackId, - int request, - ) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeCurrent", - ); - return request == _likeRequest && _likeContextCurrent(client, key, trackId); - } - - bool _likeCountCurrent( - XmlyClient client, - String key, - String trackId, - int request, - ) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeCountCurrent", - ); - return request == _likeCountRequest && - _likeContextCurrent(client, key, trackId); - } - - void _refreshLikes() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikes", - ); - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - final track = _runtime.player.current; - final sameContext = - identical(client, _likeClient) && - key == _likeKey && - track?.id == _likeTrackId; - if (sameContext && _likeBusy) return; - _likeRequest++; - _likeCountRequest++; - _likeClient = client; - _likeKey = key; - _likeTrackId = track?.id; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikes.closure#1", - ); - _likeCount = sameContext ? _likeCount ?? track?.likes : track?.likes; - if (!sameContext) _favoriteCount = null; - if (!sameContext) _liked = false; - _likeBusy = false; - _likeCountLoading = false; - _likeError = null; - _likeCountError = null; - }); - if (widget.expanded && track != null) unawaited(_refreshLikeCount(track)); - } - - Future _refreshLikeCount(Track track, {bool force = false}) async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount", - ); - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - if (!_likeContextCurrent(client, key, track.id)) return; - final request = ++_likeCountRequest; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#1", - ); - _likeCountLoading = true; - _likeCountError = null; - }); - Future<({int? likes, int? favorites})> fetch() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.fetch", - ); - if (client.accountAvailable) { - return XmlyExperience(client).trackCounts(track.id); - } - // Anonymous metadata only exposes the thumbs-up count reliably. - final forced = force || _likeCount == null; - var value = await client.track(track.id, force: forced); - if (!forced && - value.likes == null && - _likeCountCurrent(client, key, track.id, request)) { - value = await client.track(track.id, force: true); - } - return (likes: value.likes, favorites: null); - } - - try { - final value = client.accountAvailable - ? await _runtime.accounts.runWithAccount(client.identity, (admitted) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#2", - ); - if (!_likeCountCurrent(client, key, track.id, request) || - !identical(admitted, client)) { - throw const XmlyException('account_changed', '账号已变更,请重试'); - } - return fetch(); - }) - : await fetch(); - if (_likeCountCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#3", - ); - _likeCount = value.likes ?? _likeCount; - _favoriteCount = value.favorites ?? _favoriteCount; - }); - } - } catch (error, stack) { - _recordPlayerPanelError( - 'Like count failed', - error, - stack, - recoverable: true, - ); - if (_likeCountCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#4", - ); - _likeCountError = error is XmlyException - ? error.message - : '数量读取失败,请重试'; - }); - } - } finally { - if (_likeCountCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#5", - ); - _likeCountLoading = false; - }); - } - } - } - - Future _likeAction(Track track) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1", - ); - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - if (_likeBusy || !_likeContextCurrent(client, key, track.id)) { - return; - } - if (!client.accountAvailable) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#1", - ); - _likeError = '请先登录后点赞声音'; - }); - return; - } - final request = ++_likeRequest, desired = !_liked; - _likeCountRequest++; - var attempted = false; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#2", - ); - _likeBusy = true; - _likeCountLoading = false; - _likeError = null; - }); - try { - await _runtime.accounts.runWithAccount(client.identity, ( - admitted, - ) async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#3", - ); - if (!_likeCurrent(client, key, track.id, request) || - !identical(admitted, client)) { - throw const XmlyException('account_changed', '账号已变更,请重试'); - } - attempted = true; - await XmlyExperience(client).setLiked(track, liked: desired); - }); - if (_likeCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#4', - ); - _liked = desired; - }); - ScaffoldMessenger.of(context) - .showSnackBar(SnackBar(content: Text(desired ? '已点赞' : '已取消点赞'))); - } - } catch (error, stack) { - _recordPlayerPanelError('Like change failed', error, stack); - if (_likeCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#5", - ); - _likeError = error is XmlyException ? error.message : '点赞操作未完成,请重试'; - }); - } - } finally { - if (_likeCurrent(client, key, track.id, request)) { - if (attempted) await _refreshLikeCount(track, force: true); - if (_likeCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#6", - ); - _likeBusy = false; - }); - } - } - } - }); - } - - Widget _likeControl(Track? track) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeControl", - ); - final current = - track != null && - identical(_likeClient, _runtime.player.currentClient) && - _likeKey == _runtime.player.currentClient.cacheIdentity && - _likeTrackId == track.id; - final count = current ? _likeCount : null; - return Column( - mainAxisSize: MainAxisSize.min, - children: [ - PlaybackActionButton( - tooltip: - '${current && _liked - ? '取消点赞' - : _likeBusy - ? '正在处理' - : _runtime.player.currentClient.accountAvailable - ? '点赞' - : '点赞(需登录)'} · 喜欢数:${count ?? '未知'}', - onPressed: track == null || !current || _likeBusy - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeControl.closure#1", - ); - unawaited(_likeAction(track)); - }, - icon: Icon( - current && _liked - ? Icons.thumb_up_rounded - : Icons.thumb_up_outlined, - size: 20, - semanticLabel: current && _liked ? '取消点赞' : '点赞', - ), - label: count?.toString() ?? '—', - ), - if (current && _likeError != null) - SizedBox( - width: 160, - child: Text( - _likeError!, - textAlign: TextAlign.center, - style: Theme.of(context).textTheme.bodySmall, - ), - ), - if (current && _likeCountError != null) - PlaybackActionButton( - tooltip: _likeCountError!, - onPressed: _likeBusy || _likeCountLoading - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._likeControl.closure#2", - ); - unawaited(_refreshLikeCount(track, force: true)); - }, - icon: const Icon(Icons.refresh_rounded, size: 16), - label: '重试数量', - ), - ], - ); - } - - Future _refreshFavorite() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1", - ); - - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - final track = _runtime.player.current; - final request = ++_favoriteRequest; - _favoriteClient = client; - _favoriteKey = key; - _favoriteTrackId = track?.id; - _libraryRevision = _runtime.libraryRevision; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#1", - ); - - _favorite = null; - _favoriteError = null; - _favoriteBusy = track != null && client.accountAvailable; - _favoriteMutating = false; - }); - if (track == null || !client.accountAvailable) return; - try { - final favorite = await XmlyExperience(client).isFavorite(track.id); - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#2", - ); - _favorite = favorite; - }); - } - } catch (error, stack) { - _recordPlayerPanelError('Favorite status failed', error, stack); - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#3", - ); - _favoriteError = error is XmlyException - ? error.message - : '收藏状态读取失败,请重试'; - }); - } - } finally { - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#4", - ); - _favoriteBusy = false; - }); - } - } - }); - } - - Future _favoriteAction(Track track) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1", - ); - - if (_favoriteBusy || track.id != _runtime.player.current?.id) return; - final client = _runtime.player.currentClient, - key = _runtime.player.currentClient.cacheIdentity; - if (!client.accountAvailable) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#1", - ); - _favoriteError = '请先登录后收藏声音'; - }); - return; - } - final favorite = _favorite; - if (favorite == null) return _refreshFavorite(); - final request = ++_favoriteRequest, desired = !favorite; - var attempted = false; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#2", - ); - - _favoriteBusy = true; - _favoriteMutating = true; - _favoriteError = null; - }); - try { - if (favorite && - !await showConfirmationDialog(context, const Text('取消收藏此声音?'))) { - return; - } - if (!_favoriteCurrent(client, key, track.id, request)) return; - await _runtime.accounts.runWithAccount(client.identity, ( - admitted, - ) async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#3", - ); - - if (!_favoriteCurrent(client, key, track.id, request) || - !identical(admitted, client)) { - throw const XmlyException('account_changed', '账号已变更,请重试'); - } - attempted = true; - await XmlyExperience(client).setFavorite(track, favorite: desired); - }); - _runtime.libraryChanged(); - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#4", - ); - _favorite = desired; - }); - ScaffoldMessenger.of( - context, - ).showSnackBar(SnackBar(content: Text(desired ? '已收藏声音' : '已取消收藏'))); - } - } catch (error, stack) { - _recordPlayerPanelError('Favorite change failed', error, stack); - if (attempted) _runtime.libraryChanged(); - if (!_favoriteCurrent(client, key, track.id, request)) return; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#5", - ); - - _favorite = null; - _favoriteError = error is XmlyException - ? error.message - : '收藏操作未完成,请重试'; - }); - if (attempted) { - try { - final value = await XmlyExperience(client).isFavorite(track.id); - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#6", - ); - _favorite = value; - }); - } - } catch (error, stack) { - _recordPlayerPanelError( - 'Favorite reconciliation failed', - error, - stack, - recoverable: true, - ); - // Do not infer an outcome or replay an uncertain mutation. - } - } - } finally { - if (_favoriteCurrent(client, key, track.id, request)) { - if (attempted) await _refreshLikeCount(track, force: true); - } - if (_favoriteCurrent(client, key, track.id, request)) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#7", - ); - - _favoriteBusy = false; - _favoriteMutating = false; - }); - } - } - }); - } - - String get _favoriteLabel { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteLabel.get", - ); - return _favoriteBusy - ? '正在读取收藏状态' - : !_runtime.player.currentClient.accountAvailable - ? '收藏(需登录)' - : _favorite == null - ? '重试收藏状态' - : _favorite! - ? '取消收藏' - : '收藏'; - } - - Widget _favoriteControl(Track? track) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl", - ); - final current = - track != null && - identical(_likeClient, _runtime.player.currentClient) && - _likeKey == _runtime.player.currentClient.cacheIdentity && - _likeTrackId == track.id; - final count = current ? _favoriteCount : null; - if (_favoriteError == null) { - return PlaybackActionButton( - tooltip: '$_favoriteLabel · 收藏数:${count ?? '未知'}', - onPressed: track == null || _favoriteBusy - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#1", - ); - _favoriteAction(track); - }, - icon: Icon( - _favorite == true - ? Icons.favorite_rounded - : Icons.favorite_border_rounded, - size: 20, - ), - label: count?.toString() ?? '—', - ); - } - final colors = Theme.of(context).colorScheme; - return MenuAnchor( - consumeOutsideTap: true, - menuChildren: [ - SizedBox( - width: math.min(300, MediaQuery.sizeOf(context).width - 32), - child: Padding( - padding: const EdgeInsets.all(16), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('收藏状态暂不可用', style: Theme.of(context).textTheme.titleSmall), - const SizedBox(height: 8), - Text( - _favoriteError!, - style: Theme.of(context).textTheme.bodySmall, - ), - ], - ), - ), - ), - MenuItemButton( - onPressed: _favoriteBusy ? null : _refreshFavorite, - leadingIcon: const Icon(Icons.refresh_rounded), - child: const Text('重试收藏状态'), - ), - ], - builder: (context, controller, _) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#2", - ); - return PlaybackActionButton( - tooltip: '收藏状态暂不可用,点击查看', - key: const ValueKey('favoriteStatusUnavailable'), - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#2.closure#1", - ); - - controller.isOpen ? controller.close() : controller.open(); - }, - icon: Badge( - smallSize: 6, - backgroundColor: colors.outline, - child: const Icon(Icons.favorite_border_rounded, size: 20), - ), - label: count?.toString() ?? '—', - ); - }, - ); - } - - Future _act(Future Function() command) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1", - ); - - if (_busy || _cancelling) return; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#1", - ); - - _busy = true; - _error = null; - }); - try { - await command(); - } on XmlyException catch (error, stack) { - _recordPlayerPanelError('Player command failed', error, stack); - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#2", - ); - _error = error.message; - }); - } catch (error, stack) { - _recordPlayerPanelError('Player command failed', error, stack); - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#3", - ); - _error = '操作未完成,请重试'; - }); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#4", - ); - _busy = false; - }); - } - }); - } - - Future _playPause() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1", - ); - - final player = _runtime.player; - if (player.current == null || _cancelling) return; - if (!player.loading && !(_busy && player.playing)) { - return _act(player.playing ? player.pause : player.resume); - } - // Only cancellation may pass a command awaiting catalogue or audio. - // Keep its busy gate intact until that original command has settled. - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#1", - ); - - _cancelling = true; - _error = null; - }); - try { - await player.pause(); - } on XmlyException catch (error, stack) { - _recordPlayerPanelError('Player pause failed', error, stack); - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#2", - ); - _error = error.message; - }); - } catch (error, stack) { - _recordPlayerPanelError('Player pause failed', error, stack); - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#3", - ); - _error = '操作未完成,请重试'; - }); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#4", - ); - _cancelling = false; - }); - } - }); - } - - void _expand() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._expand", - ); - _navigator.push( - MaterialPageRoute( - settings: const RouteSettings(name: PlayerPanel.routeName), - builder: (_) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._expand.closure#1", - ); - return PlayerPanel(runtime: _runtime, expanded: true); - }, - ), - ); - } - - void _settings() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._settings", - ); - - final track = _runtime.player.current; - showQuickPlaybackSettings( - _navigator.context, - _runtime, - albumId: track?.albumId.isNotEmpty == true ? track!.albumId : null, - albumTitle: track?.album, - ); - } - - void _skipSegments() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._skipSegments", - ); - showSkipSegmentsSettings(_navigator.context, _runtime); - } - - void _openAlbum(String albumId) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._openAlbum", - ); - - if (albumId.isEmpty) return; - showLocalPanel( - context: _navigator.context, - title: '专辑详情', - width: 660, - height: 760, - showHeader: false, - builder: (_) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._openAlbum.closure#1", - ); - return AlbumPageView( - runtime: _runtime, - albumId: albumId, - accountIdentity: _runtime.player.libraryIdentity, - inPanel: true, - ); - }, - ); - } - - void _queue() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._queue", - ); - if (widget.expanded) { - _selectPage(3); - return; - } - showLocalPanel( - context: _navigator.context, - title: '播放列表', - width: 560, - height: 760, - builder: (_) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState._queue.closure#1', - ); - return PlayerQueuePanel( - key: ValueKey(_runtime.player), - runtime: _runtime, - ); - }, - ); - } - - Widget _cover(String? url, double size, {bool small = false}) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._cover", - ); - - final colors = Theme.of(context).colorScheme; - final fallback = ColoredBox( - color: colors.surfaceContainerHighest, - child: Center( - child: Icon( - Icons.headphones_rounded, - size: size * 0.34, - color: colors.primary, - ), - ), - ); - return ExcludeSemantics( - child: ClipRRect( - borderRadius: BorderRadius.circular(small ? 10 : 24), - child: SizedBox.square( - dimension: size, - child: url == null || url.isEmpty - ? fallback - : Image( - image: LoggedNetworkImage(url), - fit: BoxFit.cover, - errorBuilder: (_, _, _) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._cover.closure#1", - ); - return fallback; - }, - ), - ), - ), - ); - } - - Widget _button( - String label, - IconData icon, - Future Function()? command, { - double size = 56, - double iconSize = 24, - String? tooltip, - }) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._button", - ); - return PlaybackActionButton( - label: label, - showLabel: false, - tooltip: tooltip, - size: size, - onPressed: _busy || _cancelling || command == null - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState._button.closure#1", - ); - _act(command); - }, - icon: Icon(icon, size: iconSize), - ); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build", - ); - return ListenableBuilder( - listenable: _runtime, - builder: (context, _) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1", - ); - - final player = _runtime.player; - final track = player.current; - final theme = Theme.of(context); - final colors = theme.colorScheme; - final title = track == null - ? '尚未选择声音' - : track.title.isEmpty - ? track.id - : track.title; - final max = player.duration.isFinite && player.duration > 0 - ? player.duration - : 0.0; - final epoch = player.playbackEpoch; - final position = - ((_dragEpoch == epoch ? _dragPosition : null) ?? player.position) - .clamp(0.0, max) - .toDouble(); - final settings = player.effectiveSettings; - final message = _error ?? player.error ?? player.warning; - final canPause = player.playing || player.loading; - final playLabel = player.loading - ? '取消加载' - : canPause - ? '暂停' - : '播放'; - final VoidCallback? play = - track == null || _cancelling || (_busy && !canPause) - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#1", - ); - unawaited(_playPause()); - }; - final coverUrl = track?.coverUrl?.toString(); - final compact = MediaQuery.sizeOf(context).width < 400; - final widePlayer = MediaQuery.sizeOf(context).width >= 920; - Widget playControl({ - required Key key, - double size = 48, - bool coverBackground = false, - }) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.playControl', - ); - final showCover = coverBackground && coverUrl?.isNotEmpty == true; - return PlaybackActionButton( - key: key, - showLabel: false, - size: size, - emphasized: true, - label: playLabel, - tooltip: _keyHint(playLabel, '空格'), - onPressed: play, - icon: SizedBox.square( - dimension: showCover ? size - 8 : 26, - child: Stack( - alignment: Alignment.center, - children: [ - if (showCover) - Positioned.fill( - child: ClipOval( - child: Stack( - fit: StackFit.expand, - children: [ - _RotatingPlayerCover( - key: ValueKey(track!.id), - playing: player.playing, - child: _cover(coverUrl, size - 8, small: true), - ), - const ColoredBox(color: Color(0x55000000)), - ], - ), - ), - ), - if (player.loading || - player.buffering || - _busy || - _cancelling) - CircularProgressIndicator( - strokeWidth: 2, - color: showCover - ? Colors.white - : colors.onPrimaryContainer, - ), - Icon( - canPause ? Icons.pause_rounded : Icons.play_arrow_rounded, - size: 24, - color: showCover ? Colors.white : null, - ), - ], - ), - ), - ); - } - - Widget seekSlider({bool dock = false}) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider", - ); - // A track change can remount this slider while a popup excludes the - // dock's semantics. Keep its value-indicator portal in that subtree. - return Overlay.wrap( - alwaysSizeToContent: true, - clipBehavior: Clip.none, - child: SliderTheme( - data: SliderTheme.of(context).copyWith( - trackHeight: 3, - thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5), - overlayShape: const RoundSliderOverlayShape(overlayRadius: 18), - inactiveTrackColor: colors.onSurface.withValues(alpha: 0.12), - ), - child: KeyedSubtree( - key: ValueKey((player, epoch, dock)), - child: Slider( - key: dock ? const ValueKey('dockSeekSlider') : null, - padding: EdgeInsets.symmetric( - vertical: dock ? 12 : 22, - horizontal: 5, - ), - value: position, - max: max > 0 ? max : 1, - label: playbackTime(position), - semanticFormatterCallback: playbackTime, - onChangeStart: track == null || max == 0 || _busy - ? null - : (_) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#1", - ); - _dragEpoch = epoch; - }, - onChanged: track == null || max == 0 || _busy - ? null - : (value) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2", - ); - - if (_dragEpoch == epoch && - player.playbackEpoch == epoch) { - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2.closure#1", - ); - _dragPosition = value; - }); - } - }, - onChangeEnd: track == null || max == 0 || _busy - ? null - : (value) async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3", - ); - - final selectedEpoch = _dragEpoch; - setState(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#1", - ); - - _dragPosition = null; - _dragEpoch = null; - }); - if (selectedEpoch != epoch || - player.playbackEpoch != epoch) { - return; - } - await _act(() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#2", - ); - return player.seek(value, expectedEpoch: epoch); - }); - }, - ), - ), - ), - ); - } - - if (!widget.expanded) { - if (!widget.miniWindow) { - final timeStyle = theme.textTheme.bodySmall?.copyWith( - color: colors.onSurfaceVariant, - fontFeatures: const [FontFeature.tabularFigures()], - ); - return Material( - color: colors.surfaceContainerLow, - child: LayoutBuilder( - builder: (context, constraints) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#2", - ); - - final fontSize = theme.textTheme.bodyMedium?.fontSize ?? 14; - final textScale = math.max( - 1.0, - MediaQuery.textScalerOf(context).scale(fontSize) / fontSize, - ); - final availableWidth = constraints.maxWidth / textScale; - final showProgress = availableWidth >= 600; - return Padding( - key: ValueKey( - showProgress ? 'playbackDockWide' : 'playbackDockNarrow', - ), - padding: const EdgeInsets.symmetric( - horizontal: 12, - vertical: 4, - ), - child: Row( - children: [ - if (showProgress) - _button( - '上一集', - Icons.skip_previous_rounded, - track == null ? null : player.previous, - size: 48, - ), - if (showProgress) - playControl(key: const ValueKey('dockPlayPause')) - else - Semantics( - value: - '${playbackTime(position)} / ${playbackTime(max)}', - child: Stack( - children: [ - playControl( - key: const ValueKey('dockPlayPause'), - coverBackground: true, - ), - Positioned.fill( - child: IgnorePointer( - child: ExcludeSemantics( - child: CircularProgressIndicator( - value: max > 0 ? position / max : 0, - strokeWidth: 2, - strokeCap: StrokeCap.round, - backgroundColor: colors.onSurface - .withValues(alpha: 0.12), - ), - ), - ), - ), - ], - ), - ), - if (showProgress) - _button( - '下一集', - Icons.skip_next_rounded, - track == null ? null : player.next, - size: 48, - ), - const SizedBox(width: 8), - if (showProgress) ...[ - _PlayerExpandTarget( - onTap: widget.onExpand ?? _expand, - child: _cover(coverUrl, 40, small: true), - ), - const SizedBox(width: 8), - ], - Expanded( - flex: showProgress ? 2 : 1, - child: _PlayerExpandTarget( - onTap: widget.onExpand ?? _expand, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodyMedium, - ), - if (showProgress) - Text( - message ?? track?.artist ?? '', - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall?.copyWith( - color: message == null - ? colors.onSurfaceVariant - : colors.error, - ), - ), - ], - ), - ), - ), - if (showProgress) ...[ - const SizedBox(width: 16), - Expanded( - flex: 3, - child: Row( - children: [ - Expanded(child: seekSlider(dock: true)), - const SizedBox(width: 8), - Text( - '${playbackTime(position)} / ${playbackTime(max)}', - key: const ValueKey('dockPlaybackTime'), - style: timeStyle, - ), - ], - ), - ), - ], - if (availableWidth >= 760) - PlaybackSpeedControl( - runtime: _runtime, - size: 48, - albumId: track?.albumId.isNotEmpty == true - ? track!.albumId - : null, - ), - if (availableWidth >= 960) - PlaybackVolumeControl( - runtime: _runtime, - vertical: true, - size: 48, - ), - if (availableWidth >= 1080) - PlaybackModeButton(runtime: _runtime), - if (availableWidth >= 1200) - PlaybackSkipButton( - runtime: _runtime, - onPressed: _skipSegments, - ), - if (showProgress) - PlaybackActionButton( - size: 48, - tooltip: '播放列表', - label: '列表', - onPressed: _queue, - icon: const Icon(Icons.queue_music_rounded), - ), - ], - ), - ); - }, - ), - ); - } - return Material( - color: colors.surfaceContainer, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Row( - children: [ - Expanded( - child: _PlayerExpandTarget( - onTap: widget.onExpand ?? _expand, - child: Padding( - padding: const EdgeInsets.fromLTRB(10, 4, 4, 4), - child: Row( - children: [ - if (!compact) ...[ - _cover(coverUrl, 40, small: true), - const SizedBox(width: 12), - ], - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisSize: MainAxisSize.min, - children: [ - AdaptiveText( - title, - style: theme.textTheme.bodyMedium, - ), - AdaptiveText( - message ?? - (track?.album.isNotEmpty == true - ? track!.album - : '打开播放器'), - style: theme.textTheme.bodySmall - ?.copyWith( - color: message == null - ? colors.onSurfaceVariant - : colors.error, - ), - ), - ], - ), - ), - ], - ), - ), - ), - ), - playControl( - key: const ValueKey('miniPlayPause'), - coverBackground: compact, - ), - _button( - '下一集', - Icons.skip_next_rounded, - track == null ? null : player.next, - size: 48, - ), - const SizedBox(width: 4), - ], - ), - LinearProgressIndicator( - minHeight: 2, - value: - player.loading || player.buffering || _busy || _cancelling - ? null - : max > 0 - ? position / max - : 0, - backgroundColor: colors.surfaceContainerHighest, - ), - ], - ), - ); - } - - final sleep = player.policy.sleepRequest; - final remaining = player.policy.remainingDuration; - final sleepLabel = sleep == null - ? '定时关闭' - : player.policy.sleepWaitingForEnd || remaining == null - ? '本集结束后${sleep.action.name == 'exit' ? '退出' : '暂停'}' - : playbackTime(remaining.inSeconds.toDouble()); - final creatorAlbum = _creatorAlbum?.id == track?.albumId - ? _creatorAlbum - : null; - final albumArtist = creatorAlbum?.artist.trim() ?? ''; - final artist = albumArtist.isNotEmpty - ? albumArtist - : track?.artist.trim() ?? ''; - final anchorUid = creatorAlbum?.anchorUid; - final metadata = Column( - crossAxisAlignment: widePlayer - ? CrossAxisAlignment.center - : CrossAxisAlignment.start, - children: [ - Text( - title, - textAlign: widePlayer ? TextAlign.center : TextAlign.start, - maxLines: 3, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.titleLarge?.copyWith( - fontSize: compact ? 18 : 24, - height: 1.45, - fontWeight: FontWeight.w700, - ), - ), - if (track != null && - (track.albumId.isNotEmpty || - track.album.isNotEmpty || - artist.isNotEmpty)) ...[ - SizedBox(height: compact ? 4 : 10), - if (track.albumId.isNotEmpty) - TextButton( - key: const ValueKey('playerAlbumLink'), - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#3", - ); - _openAlbum(track.albumId); - }, - style: TextButton.styleFrom( - padding: const EdgeInsets.symmetric(vertical: 8), - alignment: widePlayer - ? Alignment.center - : Alignment.centerLeft, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: AdaptiveText( - track.album.isEmpty ? '查看专辑' : track.album, - style: theme.textTheme.bodySmall, - ), - ), - const Icon(Icons.chevron_right, size: 18), - ], - ), - ) - else if (track.album.isNotEmpty) - AdaptiveText( - track.album, - style: theme.textTheme.bodySmall?.copyWith( - color: colors.onSurfaceVariant, - ), - ), - if (artist.isNotEmpty) - Tooltip( - message: '查看主播:$artist', - child: TextButton( - key: const ValueKey('playerAnchorLink'), - onPressed: () { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#4', - ); - final runtime = _runtime; - final accountIdentity = runtime.player.libraryIdentity; - _navigator.push( - MaterialPageRoute( - settings: const RouteSettings( - name: AnchorPage.routeName, - ), - builder: (_) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#4.closure#1', - ); - return AnchorPage( - runtime: runtime, - uid: anchorUid, - trackId: track.id, - initialName: artist, - accountIdentity: accountIdentity, - ); - }, - ), - ); - }, - style: TextButton.styleFrom( - minimumSize: const Size(48, 48), - padding: const EdgeInsets.symmetric(vertical: 8), - alignment: widePlayer - ? Alignment.center - : Alignment.centerLeft, - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - ExcludeSemantics( - child: ClipOval( - child: CoverImage( - uri: creatorAlbum?.anchorAvatarUrl, - size: 28, - ), - ), - ), - const SizedBox(width: 8), - Flexible( - child: Text( - artist, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: theme.textTheme.bodySmall, - ), - ), - ], - ), - ), - ), - ], - ], - ); - final quickControls = Wrap( - alignment: WrapAlignment.center, - spacing: 4, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - PlaybackModeButton(runtime: _runtime), - PlaybackSpeedControl( - key: ValueKey((_runtime, track?.id)), - runtime: _runtime, - albumId: track?.albumId.isNotEmpty == true - ? track!.albumId - : null, - ), - PlaybackVolumeControl(runtime: _runtime, vertical: true), - PlaybackSkipButton(runtime: _runtime, onPressed: _skipSegments), - PlaybackActionButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#5", - ); - showSleepTimerDialog(context, _runtime); - }, - icon: Icon( - sleep == null ? Icons.timer_outlined : Icons.timer, - size: 20, - ), - label: '定时关闭', - tooltip: sleepLabel, - ), - ], - ); - final contentActions = Wrap( - alignment: WrapAlignment.center, - spacing: 4, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - _likeControl(track), - _favoriteControl(track), - PlaybackActionButton( - onPressed: track == null || _busy || _cancelling - ? null - : () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#6", - ); - _act(() async { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#6.closure#1", - ); - - final savedPosition = player.position; - await player.bookmark(); - if (context.mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text( - '已添加书签 · ${playbackTime(savedPosition)}', - ), - ), - ); - } - }); - }, - icon: const Icon(Icons.bookmark_add_outlined, size: 20), - label: '书签', - ), - PlaybackActionButton( - onPressed: _queue, - icon: const Icon(Icons.queue_music_rounded, size: 20), - label: '播放列表', - ), - ], - ); - final progress = Column( - children: [ - Row( - children: [ - _button( - '快退', - Icons.replay_rounded, - track == null ? null : player.seekBackward, - tooltip: _keyHint( - '后退 ${settings.seekBackwardSeconds} 秒', - '←', - ), - ), - Expanded(child: seekSlider()), - _button( - '快进', - Icons.forward_rounded, - track == null ? null : player.seekForward, - tooltip: _keyHint('前进 ${settings.seekForwardSeconds} 秒', '→'), - ), - ], - ), - DefaultTextStyle( - style: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( - color: colors.onSurfaceVariant, - fontFeatures: const [FontFeature.tabularFigures()], - ), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text(playbackTime(position)), - Text(playbackTime(max)), - ], - ), - ), - ], - ); - final controls = Padding( - padding: EdgeInsets.symmetric( - vertical: compact - ? 8 - : widePlayer - ? 12 - : 20, - ), - child: Wrap( - alignment: WrapAlignment.center, - spacing: 4, - runSpacing: 4, - crossAxisAlignment: WrapCrossAlignment.center, - children: [ - _button( - '上一集', - Icons.skip_previous_rounded, - track == null ? null : player.previous, - iconSize: 30, - ), - playControl( - key: const ValueKey('playerPlayPause'), - size: 64, - coverBackground: compact, - ), - _button( - '下一集', - Icons.skip_next_rounded, - track == null ? null : player.next, - iconSize: 30, - ), - ], - ), - ); - final footer = Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - if (sleep != null) - Center( - child: PlaybackActionButton( - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#7", - ); - - player.cancelSleep(); - _runtime.changed(); - }, - icon: const Icon(Icons.timer_off_outlined, size: 20), - label: '取消定时', - ), - ), - if (message != null) - Padding( - padding: const EdgeInsets.only(top: 8), - child: Text( - message, - key: const ValueKey('playerMessage'), - style: theme.textTheme.bodySmall?.copyWith( - color: colors.error, - ), - textAlign: TextAlign.center, - ), - ), - ], - ); - final page = Scaffold( - appBar: AppHeader( - leading: IconButton( - tooltip: '收起播放器', - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#8", - ); - Navigator.of(context).maybePop(); - }, - icon: const Icon(Icons.keyboard_arrow_down_rounded), - ), - title: const Text('正在收听'), - centerTitle: true, - actions: [ - IconButton( - tooltip: '播放设置', - onPressed: _settings, - icon: const Icon(Icons.settings_outlined), - ), - ], - ), - body: SafeArea( - top: false, - child: Column( - children: [ - AppTabStrip( - key: const ValueKey('playerContentTabs'), - children: [ - for (final (index, label) in [ - if (_paneCount == 1) (0, '播放'), - if (_hasManuscript) (1, '文稿'), - (2, '评论'), - (3, '播放列表'), - ]) - AppTabButton( - key: ValueKey(index), - label: label, - selected: - (_paneCount == 2 - ? _secondaryPage - : _selectedPage) == - index, - onPressed: () { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#9", - ); - _selectPage(index); - }, - ), - ], - ), - Expanded( - child: LayoutBuilder( - builder: (context, constraints) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10", - ); - final minPaneWidth = math.max( - 460.0, - MediaQuery.textScalerOf(context).scale(340), - ); - _configurePanes( - (constraints.maxWidth / minPaneWidth).floor().clamp( - 1, - 2, - ), - ); - final order = _pageOrder; - final contents = [ - LayoutBuilder( - builder: (context, constraints) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#1", - ); - final textHeight = MediaQuery.textScalerOf(context) - .scale(56); - final coverSize = math.min( - widePlayer ? 260.0 : 280.0, - math.min( - constraints.maxWidth - 64, - math.max( - 120.0, - constraints.maxHeight - - 480 - - textHeight - - (sleep == null ? 0 : 48), - ), - ), - ); - return SingleChildScrollView( - key: const PageStorageKey('playerPlayback'), - primary: false, - child: Center( - child: ConstrainedBox( - constraints: BoxConstraints( - maxWidth: widePlayer ? 560 : 680, - minHeight: constraints.maxHeight, - ), - child: Padding( - padding: EdgeInsets.all(compact ? 8 : 16), - child: Column( - mainAxisAlignment: - MainAxisAlignment.spaceEvenly, - children: [ - metadata, - const SizedBox(height: 8), - if (!compact) ...[ - _cover(coverUrl, coverSize), - const SizedBox(height: 8), - ], - controls, - progress, - contentActions, - quickControls, - footer, - ], - ), - ), - ), - ), - ); - }, - ), - !_visitedPages.contains(1) - ? const Center(child: CircularProgressIndicator()) - : _manuscriptPage(track), - !_visitedPages.contains(2) - ? const Center(child: CircularProgressIndicator()) - : track == null - ? const Center(child: Text('尚未选择声音')) - : TrackCommentsPanel( - key: ValueKey((_runtime, track.id)), - runtime: _runtime, - track: track, - ), - !_visitedPages.contains(3) - ? const SizedBox.shrink() - : PlayerQueuePanel( - key: ValueKey(_runtime.player), - runtime: _runtime, - ), - ]; - return PrimaryScrollController.none( - child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context).copyWith( - dragDevices: { - ...ScrollConfiguration.of(context).dragDevices, - PointerDeviceKind.mouse, - }, - ), - child: PageView.builder( - controller: _pages, - padEnds: false, - physics: _paneCount == 1 - ? null - : const NeverScrollableScrollPhysics(), - onPageChanged: _pageSwiped, - itemCount: order.length, - findChildIndexCallback: (key) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#2", - ); - final index = order.indexOf( - (key as ValueKey).value, - ); - return index < 0 ? null : index; - }, - itemBuilder: (context, index) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#3", - ); - final page = order[index]; - return _PlayerPage( - key: ValueKey(page), - visible: _paneCount == 2 - ? page == 0 || page == _secondaryPage - : page == _selectedPage, - child: DecoratedBox( - decoration: BoxDecoration( - border: _paneCount == 1 - ? null - : Border( - right: BorderSide( - color: colors.outlineVariant, - ), - ), - ), - child: contents[page], - ), - ); - }, - ), - ), - ); - }, - ), - ), - ], - ), - ), - ); - return _withKeyboard(page); - }, - ); - } -} - -class _PlayerPage extends StatefulWidget { - const _PlayerPage({required this.child, required this.visible, super.key}); - - final Widget child; - final bool visible; - - @override - State<_PlayerPage> createState() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPage.createState', - ); - return _PlayerPageState(); - } -} - -class _PlayerPageState extends State<_PlayerPage> - with AutomaticKeepAliveClientMixin { - Widget? _retainedChild; - @override - bool get wantKeepAlive { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPageState.wantKeepAlive.get', - ); - return true; - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_PlayerPageState.build', - ); - super.build(context); - if (widget.visible) _retainedChild = widget.child; - return _retainedChild ?? widget.child; - } -} - -class _PlayerExpandTarget extends StatefulWidget { - const _PlayerExpandTarget({required this.onTap, required this.child}); - - final VoidCallback onTap; - final Widget child; - - @override - State<_PlayerExpandTarget> createState() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerExpandTarget.createState", - ); - return _PlayerExpandTargetState(); - } -} - -class _PlayerExpandTargetState extends State<_PlayerExpandTarget> { - final _states = WidgetStatesController(); - - @override - void dispose() { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerExpandTargetState.dispose", - ); - - _states.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerExpandTargetState.build", - ); - return ListenableBuilder( - listenable: _states, - builder: (context, _) { - AppLog.instance.trace( - "lib/pages/player_panel.dart::_PlayerExpandTargetState.build.closure#1", - ); - - final radius = BorderRadius.circular(10); - return InkWell( - onTap: widget.onTap, - statesController: _states, - mouseCursor: SystemMouseCursors.click, - borderRadius: radius, - overlayColor: const WidgetStatePropertyAll(Colors.transparent), - splashFactory: NoSplash.splashFactory, - child: DecoratedBox( - decoration: BoxDecoration( - borderRadius: radius, - border: Border.all( - width: 1.5, - color: _states.value.contains(WidgetState.focused) - ? Theme.of(context).colorScheme.primary - : Colors.transparent, - ), - ), - child: widget.child, - ), - ); - }, - ); - } -} - -class _RotatingPlayerCover extends StatefulWidget { - const _RotatingPlayerCover({ - required this.playing, - required this.child, - super.key, - }); - - final bool playing; - final Widget child; - - @override - State<_RotatingPlayerCover> createState() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_RotatingPlayerCover.createState', - ); - return _RotatingPlayerCoverState(); - } -} - -class _RotatingPlayerCoverState extends State<_RotatingPlayerCover> - with SingleTickerProviderStateMixin { - late final _rotation = AnimationController( - vsync: this, - duration: const Duration(seconds: 20), - ); - - @override - void initState() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.initState', - ); - super.initState(); - if (widget.playing) _rotation.repeat(); - } - - @override - void didUpdateWidget(covariant _RotatingPlayerCover oldWidget) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.didUpdateWidget', - ); - super.didUpdateWidget(oldWidget); - if (widget.playing == oldWidget.playing) return; - if (widget.playing) { - _rotation.repeat(); - } else { - _rotation.stop(); - } - } - - @override - void dispose() { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.dispose', - ); - _rotation.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.build', - ); - return RotationTransition(turns: _rotation, child: widget.child); - } -} +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../api/xmly_client.dart'; +import '../api/xmly_experience.dart'; +import '../common/widgets/adaptive_text.dart'; +import '../common/widgets/app_header.dart'; +import '../common/widgets/app_tab_button.dart'; +import '../common/widgets/confirmation_dialog.dart'; +import '../common/widgets/logged_network_image.dart'; +import '../common/widgets/local_panel.dart'; +import '../common/widgets/playback_action_button.dart'; +import '../models/xmly_models.dart'; +import '../services/app_log.dart'; +import '../services/app_runtime.dart'; +import 'anchor_page.dart'; +import 'catalogue_page.dart'; +import 'manuscript_reader.dart'; +import 'playback_mode_control.dart'; +import 'playback_settings_page.dart'; +import 'playback_skip_control.dart'; +import 'playback_speed_control.dart'; +import 'player_queue_panel.dart'; +import 'playback_volume_control.dart'; +import 'track_comments_panel.dart'; + +void _recordPlayerPanelError( + String operation, + Object error, + StackTrace stack, { + bool recoverable = false, +}) { + AppLog.instance.trace("lib/pages/player_panel.dart::_recordPlayerPanelError"); + + final log = AppLog.instance; + if (log.errorWasRecorded(error)) return; + final expected = + error is XmlyException && + const { + 'client_closed', + 'request_cancelled', + 'cancelled', + 'download_stopped', + 'stopped', + 'closed', + 'login_required', + 'login_expired', + 'auth_required', + 'account_changed', + 'account_mismatch', + 'missing_account', + 'confirmation_required', + 'confirmation_changed', + 'insufficient_quota', + 'usage_uncertain', + 'rate_limited', + 'queue_full', + 'catalogue_limit', + 'invalid_page', + }.contains(error.code); + log.write( + recoverable || expected ? AppLogLevel.warning : AppLogLevel.error, + 'player_panel', + operation, + error: error, + stackTrace: stack, + promptUser: !recoverable && !expected, + ); +} + +String playbackTime(double seconds) { + AppLog.instance.trace("lib/pages/player_panel.dart::playbackTime"); + + final total = seconds.isFinite && seconds > 0 ? seconds.floor() : 0; + final hours = total ~/ 3600; + final minutes = (total ~/ 60) % 60; + final rest = (total % 60).toString().padLeft(2, '0'); + return hours > 0 + ? '$hours:${minutes.toString().padLeft(2, '0')}:$rest' + : '$minutes:$rest'; +} + +/// The compact player lives outside Navigator, so its measured box is the +/// shared-element destination rather than a Hero in the previous route. +class PlayerPanelRoute extends MaterialPageRoute { + PlayerPanelRoute({required AppRuntime runtime, required this.returnTarget}) + : super( + settings: const RouteSettings(name: PlayerPanel.routeName), + allowSnapshotting: false, + builder: (_) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.new.closure#1', + ); + return PlayerPanel(runtime: runtime, expanded: true); + }, + ) { + AppLog.instance.trace('lib/pages/player_panel.dart::PlayerPanelRoute.new'); + } + + final GlobalKey returnTarget; + double? _commitValue, _commitStart; + + double get expansion { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.expansion.get', + ); + final value = animation?.value ?? 0; + final start = _commitStart; + return start == null || start == 0 + ? value + : _commitValue! * (value / start).clamp(0.0, 1.0); + } + + @override + Duration get transitionDuration { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.transitionDuration.get', + ); + return const Duration(milliseconds: 300); + } + + @override + Duration get reverseTransitionDuration { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.reverseTransitionDuration.get', + ); + return const Duration(milliseconds: 260); + } + + @override + bool canTransitionFrom(TransitionRoute previousRoute) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.canTransitionFrom', + ); + return false; + } + + @override + void handleStartBackGesture({double progress = 0.0}) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.handleStartBackGesture', + ); + _commitValue = _commitStart = null; + super.handleStartBackGesture(progress: progress); + } + + @override + void handleCommitBackGesture() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.handleCommitBackGesture', + ); + _commitValue = expansion; + super.handleCommitBackGesture(); + // Flutter restarts the route controller when committing. Normalize from + // its actual new value, preserving the last interactive rectangle/opacity. + _commitStart = animation?.value; + } + + @override + Widget buildTransitions( + BuildContext context, + Animation animation, + Animation secondaryAnimation, + Widget child, + ) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::PlayerPanelRoute.buildTransitions', + ); + return _PlayerReturnTransition(route: this, child: child); + } +} + +class _PlayerReturnTransition extends StatefulWidget { + const _PlayerReturnTransition({required this.route, required this.child}); + + final PlayerPanelRoute route; + final Widget child; + + @override + State<_PlayerReturnTransition> createState() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransition.createState', + ); + return _PlayerReturnTransitionState(); + } +} + +class _PlayerReturnTransitionState extends State<_PlayerReturnTransition> + with WidgetsBindingObserver { + @override + void initState() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.initState', + ); + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.dispose', + ); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + bool handleStartBackGesture(PredictiveBackEvent event) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.handleStartBackGesture', + ); + if (event.isButtonEvent || + !widget.route.isCurrent || + !widget.route.popGestureEnabled) { + return false; + } + widget.route.handleStartBackGesture(progress: 1 - event.progress); + return true; + } + + @override + void handleUpdateBackGestureProgress(PredictiveBackEvent event) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.handleUpdateBackGestureProgress', + ); + widget.route.handleUpdateBackGestureProgress(progress: 1 - event.progress); + } + + @override + void handleCancelBackGesture() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.handleCancelBackGesture', + ); + widget.route.handleCancelBackGesture(); + } + + @override + void handleCommitBackGesture() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.handleCommitBackGesture', + ); + widget.route.handleCommitBackGesture(); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.build', + ); + return AnimatedBuilder( + animation: widget.route.animation!, + child: widget.child, + builder: (context, child) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.build.closure#1', + ); + return LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerReturnTransitionState.build.closure#1.closure#1', + ); + final expansion = widget.route.expansion; + final target = widget.route.returnTarget.currentContext + ?.findRenderObject(); + final source = context.findRenderObject(); + final size = constraints.biggest; + Rect? destination; + if (target is RenderBox && + target.attached && + target.hasSize && + source is RenderBox && + source.attached && + target.size.isFinite && + !target.size.isEmpty) { + final origin = source.globalToLocal( + target.localToGlobal(Offset.zero), + ); + final measured = origin & target.size; + if ((Offset.zero & size).contains(measured.topLeft) && + measured.right <= size.width && + measured.bottom <= size.height) { + destination = measured; + } + } + // Never shrink towards an absent/offscreen compact player. + if (destination == null || size.isEmpty) { + return Opacity(opacity: expansion, child: child); + } + final rect = Rect.lerp(destination, Offset.zero & size, expansion)!; + // Animate the container, not the page's aspect ratio. Keep its + // layout/state intact while clipping and fading toward the dock. + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fromRect( + rect: rect, + child: Opacity( + opacity: (expansion / 0.2).clamp(0.0, 1.0), + child: ClipRRect( + key: const ValueKey('playerReturnSurface'), + borderRadius: BorderRadius.circular(16 * (1 - expansion)), + child: ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: OverflowBox( + alignment: Alignment.topCenter, + minWidth: size.width, + maxWidth: size.width, + minHeight: size.height, + maxHeight: size.height, + child: Transform.scale( + scale: rect.width / size.width, + alignment: Alignment.topCenter, + child: Opacity(opacity: expansion, child: child), + ), + ), + ), + ), + ), + ), + ], + ); + }, + ); + }, + ); + } +} + +class PlayerPanel extends StatefulWidget { + const PlayerPanel({ + required this.runtime, + this.expanded = false, + this.miniWindow = false, + this.onExpand, + this.navigatorKey, + super.key, + }); + static const routeName = '/player'; + final AppRuntime runtime; + final bool expanded; + final bool miniWindow; + final VoidCallback? onExpand; + final GlobalKey? navigatorKey; + + @override + State createState() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::PlayerPanel.createState", + ); + return _PlayerPanelState(); + } +} + +class _PlayerPanelState extends State { + PageController _pages = PageController(keepPage: false); + final _retiredPages = {}; + int _paneCount = 1, _secondaryPage = 1; + (int, bool)? _pendingPaneLayout; + bool _configuredManuscript = true; + bool _changingPaneLayout = false; + final _visitedPages = {0}; + int _selectedPage = 0; + final _keyboardFocus = FocusNode( + debugLabel: 'Player shortcuts', + skipTraversal: true, + ); + bool _busy = false, _cancelling = false; + double? _dragPosition; + int? _dragEpoch; + String? _error; + XmlyClient? _favoriteClient; + String? _favoriteKey, _favoriteTrackId, _favoriteError; + bool? _favorite; + bool _favoriteBusy = false, _favoriteMutating = false; + int _favoriteRequest = 0, _libraryRevision = -1; + XmlyClient? _likeClient; + String? _likeKey, _likeTrackId, _likeError, _likeCountError; + int? _likeCount, _favoriteCount; + bool _liked = false, _likeBusy = false, _likeCountLoading = false; + int _likeRequest = 0, _likeCountRequest = 0; + XmlyClient? _manuscriptClient; + String? _manuscriptKey, _manuscriptTrackId, _manuscript, _manuscriptError; + bool _manuscriptLoading = false; + bool _manuscriptLoaded = false; + int _manuscriptRequest = 0; + Completer? _manuscriptCancelled; + Album? _creatorAlbum; + String? _creatorTrackId, _creatorAlbumId, _creatorResolvedAlbumId; + int _creatorRequest = 0; + Completer? _creatorCancelled; + AppRuntime get _runtime { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._runtime.get", + ); + return widget.runtime; + } + + NavigatorState get _navigator { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._navigator.get", + ); + return widget.navigatorKey?.currentState ?? Navigator.of(context); + } + + @override + void initState() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.initState", + ); + + super.initState(); + _runtime.addListener(_favoriteContextChanged); + _runtime.addListener(_likeContextChanged); + _runtime.addListener(_manuscriptContextChanged); + _runtime.addListener(_creatorContextChanged); + if (widget.expanded) { + unawaited(_refreshFavorite()); + _refreshLikes(); + unawaited(_refreshManuscript()); + unawaited(_refreshCreator()); + } + } + + @override + void didUpdateWidget(covariant PlayerPanel oldWidget) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.didUpdateWidget", + ); + + super.didUpdateWidget(oldWidget); + if (oldWidget.runtime != _runtime) { + oldWidget.runtime.removeListener(_favoriteContextChanged); + oldWidget.runtime.removeListener(_likeContextChanged); + oldWidget.runtime.removeListener(_manuscriptContextChanged); + oldWidget.runtime.removeListener(_creatorContextChanged); + _runtime.addListener(_manuscriptContextChanged); + _runtime.addListener(_favoriteContextChanged); + _runtime.addListener(_likeContextChanged); + _runtime.addListener(_creatorContextChanged); + _dragPosition = null; + _dragEpoch = null; + } + if (widget.expanded && + (oldWidget.runtime != _runtime || !oldWidget.expanded)) { + unawaited(_refreshFavorite()); + _refreshLikes(); + } + if (oldWidget.runtime != _runtime && !widget.expanded) _refreshLikes(); + if (oldWidget.runtime != _runtime || + oldWidget.expanded != widget.expanded) { + unawaited(_refreshManuscript()); + unawaited(_refreshCreator()); + } + } + + @override + void dispose() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.dispose", + ); + + _runtime.removeListener(_favoriteContextChanged); + _runtime.removeListener(_likeContextChanged); + _runtime.removeListener(_manuscriptContextChanged); + _runtime.removeListener(_creatorContextChanged); + _creatorRequest++; + _creatorCancelled?.complete(); + _creatorCancelled = null; + _manuscriptRequest++; + _manuscriptCancelled?.complete(); + _manuscriptCancelled = null; + _favoriteRequest++; + _likeRequest++; + _likeCountRequest++; + _pages.dispose(); + for (final controller in _retiredPages) { + controller.dispose(); + } + _retiredPages.clear(); + _keyboardFocus.dispose(); + super.dispose(); + } + + bool get _desktopKeyboard { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._desktopKeyboard.get", + ); + return switch (Theme.of(context).platform) { + TargetPlatform.windows || + TargetPlatform.macOS || + TargetPlatform.linux => true, + _ => false, + }; + } + + String _keyHint(String label, String key) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._keyHint", + ); + return _desktopKeyboard ? '$label($key)' : label; + } + + KeyEventResult _onPlayerKey(FocusNode node, KeyEvent event) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._onPlayerKey", + ); + + // Descendant controls keep their own activation, editing and navigation. + // Also exclude routes above this player, including non-focusing dialogs. + if (!node.hasPrimaryFocus || ModalRoute.of(context)?.isCurrent == false) { + return KeyEventResult.ignored; + } + final keyboard = HardwareKeyboard.instance; + if (keyboard.isControlPressed || + keyboard.isAltPressed || + keyboard.isMetaPressed || + keyboard.isShiftPressed) { + return KeyEventResult.ignored; + } + if (widget.expanded && _paneCount == 1 && _selectedPage != 0) { + return KeyEventResult.ignored; + } + final player = _runtime.player; + if (player.current == null) return KeyEventResult.ignored; + final command = switch (event.logicalKey) { + LogicalKeyboardKey.space => _playPause, + LogicalKeyboardKey.arrowLeft => player.seekBackward, + LogicalKeyboardKey.arrowRight => player.seekForward, + _ => null, + }; + if (command == null) return KeyEventResult.ignored; + // One command per press; repeats must not toggle or enqueue more seeks. + if (event is KeyDownEvent) { + unawaited( + event.logicalKey == LogicalKeyboardKey.space + ? _playPause() + : _act(command), + ); + } + return KeyEventResult.handled; + } + + Widget _withKeyboard(Widget child) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._withKeyboard", + ); + return !_desktopKeyboard + ? child + : Focus( + focusNode: _keyboardFocus, + autofocus: true, + onKeyEvent: _onPlayerKey, + child: GestureDetector( + behavior: HitTestBehavior.translucent, + onTap: _keyboardFocus.requestFocus, + child: child, + ), + ); + } + + void _creatorContextChanged() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._creatorContextChanged', + ); + if (!mounted || !widget.expanded) return; + final track = _runtime.player.current; + if (track?.id != _creatorTrackId || track?.albumId != _creatorAlbumId) { + unawaited(_refreshCreator()); + return; + } + final cached = track == null || track.albumId.isEmpty + ? null + : _runtime.albumCache[track.albumId]?.album; + if (cached?.anchorUid != null && !identical(cached, _creatorAlbum)) { + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._creatorContextChanged.closure#1', + ); + _creatorAlbum = cached; + }); + } + } + + Future _refreshCreator() async { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator', + ); + final runtime = _runtime; + final track = runtime.player.current; + final trackId = track?.id, albumId = track?.albumId; + final request = ++_creatorRequest; + _creatorCancelled?.complete(); + _creatorCancelled = null; + _creatorTrackId = trackId; + _creatorAlbumId = albumId; + final cached = albumId == null || albumId.isEmpty + ? null + : runtime.albumCache[albumId]?.album; + final previous = _creatorAlbum?.id == albumId ? _creatorAlbum : null; + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#1', + ); + _creatorAlbum = cached?.anchorUid != null ? cached : previous ?? cached; + }); + if (!widget.expanded || + trackId == null || + albumId == null || + albumId.isEmpty || + _creatorAlbum?.anchorUid != null || + (previous != null && _creatorResolvedAlbumId == albumId)) { + return; + } + final cancelled = _creatorCancelled = Completer(); + bool current() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.current', + ); + return mounted && + widget.expanded && + identical(runtime, _runtime) && + request == _creatorRequest && + runtime.player.current?.id == trackId && + runtime.player.current?.albumId == albumId; + } + + try { + final page = await runtime.anonymous.withReadPolicy( + () { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#2', + ); + return runtime.anonymous.album(albumId, pageSize: 1); + }, + rateLimitRetries: 0, + cancelled: cancelled.future, + ); + if (current() && page.album.id == albumId) { + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._refreshCreator.closure#3', + ); + _creatorAlbum = page.album; + _creatorResolvedAlbumId = albumId; + }); + } + } catch (error, stack) { + if (current()) { + _recordPlayerPanelError( + 'Player creator load failed', + error, + stack, + recoverable: true, + ); + } + } finally { + if (current()) _creatorCancelled = null; + } + } + + void _manuscriptContextChanged() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._manuscriptContextChanged", + ); + + if (!mounted || !widget.expanded) return; + final client = _runtime.player.currentClient; + if (!identical(client, _manuscriptClient) || + client.cacheIdentity != _manuscriptKey || + _runtime.player.current?.id != _manuscriptTrackId) { + unawaited(_refreshManuscript()); + } + } + + Future _refreshManuscript({bool force = false}) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1", + ); + + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + final trackId = _runtime.player.current?.id; + if (!force && + widget.expanded && + identical(client, _manuscriptClient) && + key == _manuscriptKey && + trackId == _manuscriptTrackId && + (_manuscriptLoaded || _manuscriptLoading)) { + return; + } + final request = ++_manuscriptRequest; + _manuscriptCancelled?.complete(); + _manuscriptCancelled = null; + _manuscriptClient = client; + _manuscriptKey = key; + _manuscriptTrackId = trackId; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#1", + ); + + _manuscript = null; + _manuscriptError = null; + _manuscriptLoaded = false; + _manuscriptLoading = widget.expanded && trackId != null; + }); + if (!_manuscriptLoading) return; + final cancelled = _manuscriptCancelled = Completer(); + bool current() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.current", + ); + return mounted && + widget.expanded && + request == _manuscriptRequest && + identical(client, _runtime.player.currentClient) && + key == _runtime.player.currentClient.cacheIdentity && + trackId == _runtime.player.current?.id; + } + + try { + final manuscript = await client.withReadPolicy( + () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#2", + ); + return client.fetchManuscript(trackId!); + }, + rateLimitRetries: 0, + cancelled: cancelled.future, + ); + if (current()) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#3", + ); + + _manuscript = manuscript; + _manuscriptLoaded = true; + if (manuscript == null) { + if (_selectedPage == 1) _selectedPage = 2; + if (_secondaryPage == 1) _secondaryPage = 2; + if (_paneCount == 2 || _selectedPage == 2) { + _visitedPages.add(2); + } + } + }); + } + } catch (error, stack) { + _recordPlayerPanelError('Manuscript load failed', error, stack); + if (current()) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#4", + ); + _manuscriptError = error is XmlyException + ? error.message + : '文稿读取失败,请重试'; + }); + } + } finally { + if (current()) { + _manuscriptCancelled = null; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshManuscript.closure#1.closure#5", + ); + _manuscriptLoading = false; + }); + } + } + }); + } + + void _selectPage(int page) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._selectPage', + ); + if (!_pageOrder.contains(page)) return; + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._selectPage.closure#1', + ); + _selectedPage = page; + if (page != 0) _secondaryPage = page; + _visitedPages.add(page); + }); + if (_paneCount == 1 && _pages.hasClients && !_changingPaneLayout) { + unawaited( + _pages.animateToPage( + _pageOrder.indexOf(page), + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 250), + curve: Curves.easeOutCubic, + ), + ); + } + } + + bool get _hasManuscript { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._hasManuscript.get', + ); + return !_manuscriptLoaded || _manuscript != null; + } + + List get _pageOrder { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._pageOrder.get', + ); + final secondary = [if (_hasManuscript) 1, 2, 3]; + return [ + 0, + if (_paneCount == 2) _secondaryPage, + for (final page in secondary) + if (_paneCount == 1 || page != _secondaryPage) page, + ]; + } + + void _configurePanes(int count) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes', + ); + final layout = (count, _hasManuscript); + if (count == _paneCount && _hasManuscript == _configuredManuscript) { + _pendingPaneLayout = null; + return; + } + if (layout == _pendingPaneLayout) return; + _pendingPaneLayout = layout; + WidgetsBinding.instance.addPostFrameCallback((_) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1', + ); + if (!mounted || _pendingPaneLayout != layout) return; + _pendingPaneLayout = null; + final oldPages = _pages; + _changingPaneLayout = true; + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1.closure#1', + ); + _paneCount = count; + _configuredManuscript = _hasManuscript; + _pages = PageController( + keepPage: false, + viewportFraction: 1 / count, + initialPage: count == 1 ? _pageOrder.indexOf(_selectedPage) : 0, + ); + if (count == 2) _visitedPages.add(_secondaryPage); + }); + final installedPages = _pages; + _retiredPages.add(oldPages); + WidgetsBinding.instance.addPostFrameCallback((_) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._configurePanes.closure#1.closure#2', + ); + if (mounted && identical(_pages, installedPages)) { + if (installedPages.hasClients) { + installedPages.jumpToPage( + count == 1 ? _pageOrder.indexOf(_selectedPage) : 0, + ); + } + _changingPaneLayout = false; + } + if (_retiredPages.remove(oldPages)) oldPages.dispose(); + }); + }); + } + + void _pageSwiped(int index) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._pageSwiped', + ); + if (_paneCount != 1 || _changingPaneLayout) return; + final order = _pageOrder; + if (index >= order.length) return; + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._pageSwiped.closure#1', + ); + _selectedPage = order[index]; + if (_selectedPage != 0) _secondaryPage = _selectedPage; + _visitedPages.add(_selectedPage); + }); + } + + Widget _manuscriptPage(Track? track) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._manuscriptPage', + ); + if (track == null) return const Center(child: Text('尚未选择声音')); + if (_manuscriptLoading) { + return const Center(child: CircularProgressIndicator()); + } + if (_manuscriptError != null) { + return Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(_manuscriptError!, textAlign: TextAlign.center), + PlaybackActionButton( + onPressed: () { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._manuscriptPage.closure#1', + ); + unawaited(_refreshManuscript(force: true)); + }, + icon: const Icon(Icons.refresh), + label: '重试文稿', + ), + ], + ), + ), + ); + } + if (_manuscript == null) { + return const Center(child: Text('此声音暂无文稿')); + } + return Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 900), + child: ManuscriptReader( + key: ValueKey(( + _manuscriptClient, + _manuscriptKey, + _manuscriptTrackId, + )), + manuscript: _manuscript!, + showTitle: false, + ), + ), + ); + } + + void _favoriteContextChanged() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteContextChanged", + ); + + if (!widget.expanded || !mounted) return; + final client = _runtime.player.currentClient; + final changed = + !identical(client, _favoriteClient) || + client.cacheIdentity != _favoriteKey || + _runtime.player.current?.id != _favoriteTrackId; + final revised = _libraryRevision != _runtime.libraryRevision; + _libraryRevision = _runtime.libraryRevision; + if (changed || (revised && !_favoriteMutating)) { + unawaited(_refreshFavorite()); + final track = _runtime.player.current; + if (!changed && track != null) { + unawaited(_refreshLikeCount(track, force: true)); + } + } + } + + bool _favoriteCurrent( + XmlyClient client, + String key, + String trackId, + int request, + ) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteCurrent", + ); + return mounted && + request == _favoriteRequest && + identical(client, _runtime.player.currentClient) && + key == _runtime.player.currentClient.cacheIdentity && + trackId == _runtime.player.current?.id; + } + + void _likeContextChanged() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeContextChanged", + ); + if (!mounted) return; + final client = _runtime.player.currentClient; + if (!identical(client, _likeClient) || + client.cacheIdentity != _likeKey || + _runtime.player.current?.id != _likeTrackId) { + _refreshLikes(); + } + } + + bool _likeContextCurrent(XmlyClient client, String key, String trackId) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeContextCurrent", + ); + return mounted && + identical(client, _runtime.player.currentClient) && + key == _runtime.player.currentClient.cacheIdentity && + trackId == _runtime.player.current?.id; + } + + bool _likeCurrent( + XmlyClient client, + String key, + String trackId, + int request, + ) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeCurrent", + ); + return request == _likeRequest && _likeContextCurrent(client, key, trackId); + } + + bool _likeCountCurrent( + XmlyClient client, + String key, + String trackId, + int request, + ) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeCountCurrent", + ); + return request == _likeCountRequest && + _likeContextCurrent(client, key, trackId); + } + + void _refreshLikes() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikes", + ); + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + final track = _runtime.player.current; + final sameContext = + identical(client, _likeClient) && + key == _likeKey && + track?.id == _likeTrackId; + if (sameContext && _likeBusy) return; + _likeRequest++; + _likeCountRequest++; + _likeClient = client; + _likeKey = key; + _likeTrackId = track?.id; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikes.closure#1", + ); + _likeCount = sameContext ? _likeCount ?? track?.likes : track?.likes; + if (!sameContext) _favoriteCount = null; + if (!sameContext) _liked = false; + _likeBusy = false; + _likeCountLoading = false; + _likeError = null; + _likeCountError = null; + }); + if (widget.expanded && track != null) unawaited(_refreshLikeCount(track)); + } + + Future _refreshLikeCount(Track track, {bool force = false}) async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount", + ); + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + if (!_likeContextCurrent(client, key, track.id)) return; + final request = ++_likeCountRequest; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#1", + ); + _likeCountLoading = true; + _likeCountError = null; + }); + Future<({int? likes, int? favorites})> fetch() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.fetch", + ); + if (client.accountAvailable) { + return XmlyExperience(client).trackCounts(track.id); + } + // Anonymous metadata only exposes the thumbs-up count reliably. + final forced = force || _likeCount == null; + var value = await client.track(track.id, force: forced); + if (!forced && + value.likes == null && + _likeCountCurrent(client, key, track.id, request)) { + value = await client.track(track.id, force: true); + } + return (likes: value.likes, favorites: null); + } + + try { + final value = client.accountAvailable + ? await _runtime.accounts.runWithAccount(client.identity, (admitted) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#2", + ); + if (!_likeCountCurrent(client, key, track.id, request) || + !identical(admitted, client)) { + throw const XmlyException('account_changed', '账号已变更,请重试'); + } + return fetch(); + }) + : await fetch(); + if (_likeCountCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#3", + ); + _likeCount = value.likes ?? _likeCount; + _favoriteCount = value.favorites ?? _favoriteCount; + }); + } + } catch (error, stack) { + _recordPlayerPanelError( + 'Like count failed', + error, + stack, + recoverable: true, + ); + if (_likeCountCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#4", + ); + _likeCountError = error is XmlyException + ? error.message + : '数量读取失败,请重试'; + }); + } + } finally { + if (_likeCountCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshLikeCount.closure#5", + ); + _likeCountLoading = false; + }); + } + } + } + + Future _likeAction(Track track) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1", + ); + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + if (_likeBusy || !_likeContextCurrent(client, key, track.id)) { + return; + } + if (!client.accountAvailable) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#1", + ); + _likeError = '请先登录后点赞声音'; + }); + return; + } + final request = ++_likeRequest, desired = !_liked; + _likeCountRequest++; + var attempted = false; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#2", + ); + _likeBusy = true; + _likeCountLoading = false; + _likeError = null; + }); + try { + await _runtime.accounts.runWithAccount(client.identity, ( + admitted, + ) async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#3", + ); + if (!_likeCurrent(client, key, track.id, request) || + !identical(admitted, client)) { + throw const XmlyException('account_changed', '账号已变更,请重试'); + } + attempted = true; + await XmlyExperience(client).setLiked(track, liked: desired); + }); + if (_likeCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#4', + ); + _liked = desired; + }); + ScaffoldMessenger.of(context) + .showSnackBar(SnackBar(content: Text(desired ? '已点赞' : '已取消点赞'))); + } + } catch (error, stack) { + _recordPlayerPanelError('Like change failed', error, stack); + if (_likeCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#5", + ); + _likeError = error is XmlyException ? error.message : '点赞操作未完成,请重试'; + }); + } + } finally { + if (_likeCurrent(client, key, track.id, request)) { + if (attempted) await _refreshLikeCount(track, force: true); + if (_likeCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeAction.closure#1.closure#6", + ); + _likeBusy = false; + }); + } + } + } + }); + } + + Widget _likeControl(Track? track) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeControl", + ); + final current = + track != null && + identical(_likeClient, _runtime.player.currentClient) && + _likeKey == _runtime.player.currentClient.cacheIdentity && + _likeTrackId == track.id; + final count = current ? _likeCount : null; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + PlaybackActionButton( + tooltip: + '${current && _liked + ? '取消点赞' + : _likeBusy + ? '正在处理' + : _runtime.player.currentClient.accountAvailable + ? '点赞' + : '点赞(需登录)'} · 喜欢数:${count ?? '未知'}', + onPressed: track == null || !current || _likeBusy + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeControl.closure#1", + ); + unawaited(_likeAction(track)); + }, + icon: Icon( + current && _liked + ? Icons.thumb_up_rounded + : Icons.thumb_up_outlined, + size: 20, + semanticLabel: current && _liked ? '取消点赞' : '点赞', + ), + label: count?.toString() ?? '—', + ), + if (current && _likeError != null) + SizedBox( + width: 160, + child: Text( + _likeError!, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + if (current && _likeCountError != null) + PlaybackActionButton( + tooltip: _likeCountError!, + onPressed: _likeBusy || _likeCountLoading + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._likeControl.closure#2", + ); + unawaited(_refreshLikeCount(track, force: true)); + }, + icon: const Icon(Icons.refresh_rounded, size: 16), + label: '重试数量', + ), + ], + ); + } + + Future _refreshFavorite() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1", + ); + + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + final track = _runtime.player.current; + final request = ++_favoriteRequest; + _favoriteClient = client; + _favoriteKey = key; + _favoriteTrackId = track?.id; + _libraryRevision = _runtime.libraryRevision; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#1", + ); + + _favorite = null; + _favoriteError = null; + _favoriteBusy = track != null && client.accountAvailable; + _favoriteMutating = false; + }); + if (track == null || !client.accountAvailable) return; + try { + final favorite = await XmlyExperience(client).isFavorite(track.id); + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#2", + ); + _favorite = favorite; + }); + } + } catch (error, stack) { + _recordPlayerPanelError('Favorite status failed', error, stack); + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#3", + ); + _favoriteError = error is XmlyException + ? error.message + : '收藏状态读取失败,请重试'; + }); + } + } finally { + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._refreshFavorite.closure#1.closure#4", + ); + _favoriteBusy = false; + }); + } + } + }); + } + + Future _favoriteAction(Track track) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1", + ); + + if (_favoriteBusy || track.id != _runtime.player.current?.id) return; + final client = _runtime.player.currentClient, + key = _runtime.player.currentClient.cacheIdentity; + if (!client.accountAvailable) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#1", + ); + _favoriteError = '请先登录后收藏声音'; + }); + return; + } + final favorite = _favorite; + if (favorite == null) return _refreshFavorite(); + final request = ++_favoriteRequest, desired = !favorite; + var attempted = false; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#2", + ); + + _favoriteBusy = true; + _favoriteMutating = true; + _favoriteError = null; + }); + try { + if (favorite && + !await showConfirmationDialog(context, const Text('取消收藏此声音?'))) { + return; + } + if (!_favoriteCurrent(client, key, track.id, request)) return; + await _runtime.accounts.runWithAccount(client.identity, ( + admitted, + ) async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#3", + ); + + if (!_favoriteCurrent(client, key, track.id, request) || + !identical(admitted, client)) { + throw const XmlyException('account_changed', '账号已变更,请重试'); + } + attempted = true; + await XmlyExperience(client).setFavorite(track, favorite: desired); + }); + _runtime.libraryChanged(); + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#4", + ); + _favorite = desired; + }); + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(desired ? '已收藏声音' : '已取消收藏'))); + } + } catch (error, stack) { + _recordPlayerPanelError('Favorite change failed', error, stack); + if (attempted) _runtime.libraryChanged(); + if (!_favoriteCurrent(client, key, track.id, request)) return; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#5", + ); + + _favorite = null; + _favoriteError = error is XmlyException + ? error.message + : '收藏操作未完成,请重试'; + }); + if (attempted) { + try { + final value = await XmlyExperience(client).isFavorite(track.id); + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#6", + ); + _favorite = value; + }); + } + } catch (error, stack) { + _recordPlayerPanelError( + 'Favorite reconciliation failed', + error, + stack, + recoverable: true, + ); + // Do not infer an outcome or replay an uncertain mutation. + } + } + } finally { + if (_favoriteCurrent(client, key, track.id, request)) { + if (attempted) await _refreshLikeCount(track, force: true); + } + if (_favoriteCurrent(client, key, track.id, request)) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteAction.closure#1.closure#7", + ); + + _favoriteBusy = false; + _favoriteMutating = false; + }); + } + } + }); + } + + String get _favoriteLabel { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteLabel.get", + ); + return _favoriteBusy + ? '正在读取收藏状态' + : !_runtime.player.currentClient.accountAvailable + ? '收藏(需登录)' + : _favorite == null + ? '重试收藏状态' + : _favorite! + ? '取消收藏' + : '收藏'; + } + + Widget _favoriteControl(Track? track) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl", + ); + final current = + track != null && + identical(_likeClient, _runtime.player.currentClient) && + _likeKey == _runtime.player.currentClient.cacheIdentity && + _likeTrackId == track.id; + final count = current ? _favoriteCount : null; + if (_favoriteError == null) { + return PlaybackActionButton( + tooltip: '$_favoriteLabel · 收藏数:${count ?? '未知'}', + onPressed: track == null || _favoriteBusy + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#1", + ); + _favoriteAction(track); + }, + icon: Icon( + _favorite == true + ? Icons.favorite_rounded + : Icons.favorite_border_rounded, + size: 20, + ), + label: count?.toString() ?? '—', + ); + } + final colors = Theme.of(context).colorScheme; + return MenuAnchor( + consumeOutsideTap: true, + menuChildren: [ + SizedBox( + width: math.min(300, MediaQuery.sizeOf(context).width - 32), + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('收藏状态暂不可用', style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: 8), + Text( + _favoriteError!, + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ), + ), + MenuItemButton( + onPressed: _favoriteBusy ? null : _refreshFavorite, + leadingIcon: const Icon(Icons.refresh_rounded), + child: const Text('重试收藏状态'), + ), + ], + builder: (context, controller, _) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#2", + ); + return PlaybackActionButton( + tooltip: '收藏状态暂不可用,点击查看', + key: const ValueKey('favoriteStatusUnavailable'), + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._favoriteControl.closure#2.closure#1", + ); + + controller.isOpen ? controller.close() : controller.open(); + }, + icon: Badge( + smallSize: 6, + backgroundColor: colors.outline, + child: const Icon(Icons.favorite_border_rounded, size: 20), + ), + label: count?.toString() ?? '—', + ); + }, + ); + } + + Future _act(Future Function() command) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1", + ); + + if (_busy || _cancelling) return; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#1", + ); + + _busy = true; + _error = null; + }); + try { + await command(); + } on XmlyException catch (error, stack) { + _recordPlayerPanelError('Player command failed', error, stack); + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#2", + ); + _error = error.message; + }); + } catch (error, stack) { + _recordPlayerPanelError('Player command failed', error, stack); + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#3", + ); + _error = '操作未完成,请重试'; + }); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._act.closure#1.closure#4", + ); + _busy = false; + }); + } + }); + } + + Future _playPause() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1", + ); + + final player = _runtime.player; + if (player.current == null || _cancelling) return; + if (!player.loading && !(_busy && player.playing)) { + return _act(player.playing ? player.pause : player.resume); + } + // Only cancellation may pass a command awaiting catalogue or audio. + // Keep its busy gate intact until that original command has settled. + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#1", + ); + + _cancelling = true; + _error = null; + }); + try { + await player.pause(); + } on XmlyException catch (error, stack) { + _recordPlayerPanelError('Player pause failed', error, stack); + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#2", + ); + _error = error.message; + }); + } catch (error, stack) { + _recordPlayerPanelError('Player pause failed', error, stack); + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#3", + ); + _error = '操作未完成,请重试'; + }); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._playPause.closure#1.closure#4", + ); + _cancelling = false; + }); + } + }); + } + + void _expand() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._expand", + ); + _navigator.push( + MaterialPageRoute( + settings: const RouteSettings(name: PlayerPanel.routeName), + builder: (_) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._expand.closure#1", + ); + return PlayerPanel(runtime: _runtime, expanded: true); + }, + ), + ); + } + + void _settings() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._settings", + ); + + final track = _runtime.player.current; + showQuickPlaybackSettings( + _navigator.context, + _runtime, + albumId: track?.albumId.isNotEmpty == true ? track!.albumId : null, + albumTitle: track?.album, + ); + } + + void _skipSegments() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._skipSegments", + ); + showSkipSegmentsSettings(_navigator.context, _runtime); + } + + void _openAlbum(String albumId) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._openAlbum", + ); + + if (albumId.isEmpty) return; + showLocalPanel( + context: _navigator.context, + title: '专辑详情', + width: 660, + height: 760, + showHeader: false, + builder: (_) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._openAlbum.closure#1", + ); + return AlbumPageView( + runtime: _runtime, + albumId: albumId, + accountIdentity: _runtime.player.libraryIdentity, + inPanel: true, + ); + }, + ); + } + + void _queue() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._queue", + ); + if (widget.expanded) { + _selectPage(3); + return; + } + showLocalPanel( + context: _navigator.context, + title: '播放列表', + width: 560, + height: 760, + builder: (_) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState._queue.closure#1', + ); + return PlayerQueuePanel( + key: ValueKey(_runtime.player), + runtime: _runtime, + ); + }, + ); + } + + Widget _cover(String? url, double size, {bool small = false}) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._cover", + ); + + final colors = Theme.of(context).colorScheme; + final fallback = ColoredBox( + color: colors.surfaceContainerHighest, + child: Center( + child: Icon( + Icons.headphones_rounded, + size: size * 0.34, + color: colors.primary, + ), + ), + ); + return ExcludeSemantics( + child: ClipRRect( + borderRadius: BorderRadius.circular(small ? 10 : 24), + child: SizedBox.square( + dimension: size, + child: url == null || url.isEmpty + ? fallback + : Image( + image: LoggedNetworkImage(url), + fit: BoxFit.cover, + errorBuilder: (_, _, _) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._cover.closure#1", + ); + return fallback; + }, + ), + ), + ), + ); + } + + Widget _button( + String label, + IconData icon, + Future Function()? command, { + double size = 56, + double iconSize = 24, + String? tooltip, + }) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._button", + ); + return PlaybackActionButton( + label: label, + showLabel: false, + tooltip: tooltip, + size: size, + onPressed: _busy || _cancelling || command == null + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState._button.closure#1", + ); + _act(command); + }, + icon: Icon(icon, size: iconSize), + ); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build", + ); + return ListenableBuilder( + listenable: _runtime, + builder: (context, _) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1", + ); + + final player = _runtime.player; + final track = player.current; + final theme = Theme.of(context); + final colors = theme.colorScheme; + final title = track == null + ? '尚未选择声音' + : track.title.isEmpty + ? track.id + : track.title; + final max = player.duration.isFinite && player.duration > 0 + ? player.duration + : 0.0; + final epoch = player.playbackEpoch; + final position = + ((_dragEpoch == epoch ? _dragPosition : null) ?? player.position) + .clamp(0.0, max) + .toDouble(); + final settings = player.effectiveSettings; + final message = _error ?? player.error ?? player.warning; + final canPause = player.playing || player.loading; + final playLabel = player.loading + ? '取消加载' + : canPause + ? '暂停' + : '播放'; + final VoidCallback? play = + track == null || _cancelling || (_busy && !canPause) + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#1", + ); + unawaited(_playPause()); + }; + final coverUrl = track?.coverUrl?.toString(); + final compact = MediaQuery.sizeOf(context).width < 400; + final widePlayer = MediaQuery.sizeOf(context).width >= 920; + Widget playControl({ + required Key key, + double size = 48, + bool coverBackground = false, + }) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.playControl', + ); + final showCover = coverBackground && coverUrl?.isNotEmpty == true; + return PlaybackActionButton( + key: key, + showLabel: false, + size: size, + emphasized: true, + label: playLabel, + tooltip: _keyHint(playLabel, '空格'), + onPressed: play, + icon: SizedBox.square( + dimension: showCover ? size - 8 : 26, + child: Stack( + alignment: Alignment.center, + children: [ + if (showCover) + Positioned.fill( + child: ClipOval( + child: Stack( + fit: StackFit.expand, + children: [ + _RotatingPlayerCover( + key: ValueKey(track!.id), + playing: player.playing, + child: _cover(coverUrl, size - 8, small: true), + ), + const ColoredBox(color: Color(0x55000000)), + ], + ), + ), + ), + if (player.loading || + player.buffering || + _busy || + _cancelling) + CircularProgressIndicator( + strokeWidth: 2, + color: showCover + ? Colors.white + : colors.onPrimaryContainer, + ), + Icon( + canPause ? Icons.pause_rounded : Icons.play_arrow_rounded, + size: 24, + color: showCover ? Colors.white : null, + ), + ], + ), + ), + ); + } + + Widget seekSlider({bool dock = false}) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider", + ); + // A track change can remount this slider while a popup excludes the + // dock's semantics. Keep its value-indicator portal in that subtree. + final slider = Overlay.wrap( + alwaysSizeToContent: true, + clipBehavior: Clip.none, + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 3, + thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 5), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 18), + inactiveTrackColor: colors.onSurface.withValues(alpha: 0.12), + ), + child: KeyedSubtree( + key: ValueKey((player, epoch, dock)), + child: Slider( + key: dock ? const ValueKey('dockSeekSlider') : null, + padding: EdgeInsets.symmetric( + vertical: dock ? 12 : 22, + horizontal: 5, + ), + value: position, + max: max > 0 ? max : 1, + label: playbackTime(position), + semanticFormatterCallback: playbackTime, + onChangeStart: track == null || max == 0 || _busy + ? null + : (_) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#1", + ); + _dragEpoch = epoch; + }, + onChanged: track == null || max == 0 || _busy + ? null + : (value) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2", + ); + + if (_dragEpoch == epoch && + player.playbackEpoch == epoch) { + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#2.closure#1", + ); + _dragPosition = value; + }); + } + }, + onChangeEnd: track == null || max == 0 || _busy + ? null + : (value) async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3", + ); + + final selectedEpoch = _dragEpoch; + setState(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#1", + ); + + _dragPosition = null; + _dragEpoch = null; + }); + if (selectedEpoch != epoch || + player.playbackEpoch != epoch) { + return; + } + await _act(() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.seekSlider.closure#3.closure#2", + ); + return player.seek(value, expectedEpoch: epoch); + }); + }, + ), + ), + ), + ); + // A bounded-height Row makes Slider consume all remaining height. + // Constrain only the dock control, not its text or the full player. + return dock + ? SizedBox(height: kMinInteractiveDimension, child: slider) + : slider; + } + + if (!widget.expanded) { + if (!widget.miniWindow) { + final timeStyle = theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + fontFeatures: const [FontFeature.tabularFigures()], + ); + return Material( + color: colors.surfaceContainerLow, + child: LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#2", + ); + + final fontSize = theme.textTheme.bodyMedium?.fontSize ?? 14; + final textScale = math.max( + 1.0, + MediaQuery.textScalerOf(context).scale(fontSize) / fontSize, + ); + final availableWidth = constraints.maxWidth / textScale; + final showProgress = availableWidth >= 600; + return Padding( + key: ValueKey( + showProgress ? 'playbackDockWide' : 'playbackDockNarrow', + ), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 4, + ), + child: Row( + children: [ + if (showProgress) + _button( + '上一集', + Icons.skip_previous_rounded, + track == null ? null : player.previous, + size: 48, + ), + if (showProgress) + playControl(key: const ValueKey('dockPlayPause')) + else + Semantics( + value: + '${playbackTime(position)} / ${playbackTime(max)}', + child: Stack( + children: [ + playControl( + key: const ValueKey('dockPlayPause'), + coverBackground: true, + ), + Positioned.fill( + child: IgnorePointer( + child: ExcludeSemantics( + child: CircularProgressIndicator( + value: max > 0 ? position / max : 0, + strokeWidth: 2, + strokeCap: StrokeCap.round, + backgroundColor: colors.onSurface + .withValues(alpha: 0.12), + ), + ), + ), + ), + ], + ), + ), + if (showProgress) + _button( + '下一集', + Icons.skip_next_rounded, + track == null ? null : player.next, + size: 48, + ), + const SizedBox(width: 8), + if (showProgress) ...[ + _PlayerExpandTarget( + onTap: widget.onExpand ?? _expand, + child: _cover(coverUrl, 40, small: true), + ), + const SizedBox(width: 8), + ], + Expanded( + flex: showProgress ? 2 : 1, + child: _PlayerExpandTarget( + onTap: widget.onExpand ?? _expand, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium, + ), + if (showProgress) + Text( + message ?? track?.artist ?? '', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall?.copyWith( + color: message == null + ? colors.onSurfaceVariant + : colors.error, + ), + ), + ], + ), + ), + ), + if (showProgress) ...[ + const SizedBox(width: 16), + Expanded( + flex: 3, + child: Row( + children: [ + Expanded(child: seekSlider(dock: true)), + const SizedBox(width: 8), + Text( + '${playbackTime(position)} / ${playbackTime(max)}', + key: const ValueKey('dockPlaybackTime'), + style: timeStyle, + ), + ], + ), + ), + ], + if (availableWidth >= 760) + PlaybackSpeedControl( + runtime: _runtime, + size: 48, + albumId: track?.albumId.isNotEmpty == true + ? track!.albumId + : null, + ), + if (availableWidth >= 960) + PlaybackVolumeControl( + runtime: _runtime, + vertical: true, + size: 48, + ), + if (availableWidth >= 1080) + PlaybackModeButton(runtime: _runtime), + if (availableWidth >= 1200) + PlaybackSkipButton( + runtime: _runtime, + onPressed: _skipSegments, + ), + if (showProgress) + PlaybackActionButton( + size: 48, + tooltip: '播放列表', + label: '列表', + onPressed: _queue, + icon: const Icon(Icons.queue_music_rounded), + ), + ], + ), + ); + }, + ), + ); + } + return Material( + color: colors.surfaceContainer, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Expanded( + child: _PlayerExpandTarget( + onTap: widget.onExpand ?? _expand, + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 4, 4, 4), + child: Row( + children: [ + if (!compact) ...[ + _cover(coverUrl, 40, small: true), + const SizedBox(width: 12), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + AdaptiveText( + title, + style: theme.textTheme.bodyMedium, + ), + AdaptiveText( + message ?? + (track?.album.isNotEmpty == true + ? track!.album + : '打开播放器'), + style: theme.textTheme.bodySmall + ?.copyWith( + color: message == null + ? colors.onSurfaceVariant + : colors.error, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + playControl( + key: const ValueKey('miniPlayPause'), + coverBackground: compact, + ), + _button( + '下一集', + Icons.skip_next_rounded, + track == null ? null : player.next, + size: 48, + ), + const SizedBox(width: 4), + ], + ), + LinearProgressIndicator( + minHeight: 2, + value: + player.loading || player.buffering || _busy || _cancelling + ? null + : max > 0 + ? position / max + : 0, + backgroundColor: colors.surfaceContainerHighest, + ), + ], + ), + ); + } + + final sleep = player.policy.sleepRequest; + final remaining = player.policy.remainingDuration; + final sleepLabel = sleep == null + ? '定时关闭' + : player.policy.sleepWaitingForEnd || remaining == null + ? '本集结束后${sleep.action.name == 'exit' ? '退出' : '暂停'}' + : playbackTime(remaining.inSeconds.toDouble()); + final creatorAlbum = _creatorAlbum?.id == track?.albumId + ? _creatorAlbum + : null; + final albumArtist = creatorAlbum?.artist.trim() ?? ''; + final artist = albumArtist.isNotEmpty + ? albumArtist + : track?.artist.trim() ?? ''; + final anchorUid = creatorAlbum?.anchorUid; + final metadata = Column( + crossAxisAlignment: widePlayer + ? CrossAxisAlignment.center + : CrossAxisAlignment.start, + children: [ + Text( + title, + textAlign: widePlayer ? TextAlign.center : TextAlign.start, + maxLines: 3, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleLarge?.copyWith( + fontSize: compact ? 18 : 24, + height: 1.45, + fontWeight: FontWeight.w700, + ), + ), + if (track != null && + (track.albumId.isNotEmpty || + track.album.isNotEmpty || + artist.isNotEmpty)) ...[ + SizedBox(height: compact ? 4 : 10), + if (track.albumId.isNotEmpty) + TextButton( + key: const ValueKey('playerAlbumLink'), + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#3", + ); + _openAlbum(track.albumId); + }, + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric(vertical: 8), + alignment: widePlayer + ? Alignment.center + : Alignment.centerLeft, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: AdaptiveText( + track.album.isEmpty ? '查看专辑' : track.album, + style: theme.textTheme.bodySmall, + ), + ), + const Icon(Icons.chevron_right, size: 18), + ], + ), + ) + else if (track.album.isNotEmpty) + AdaptiveText( + track.album, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + if (artist.isNotEmpty) + Tooltip( + message: '查看主播:$artist', + child: TextButton( + key: const ValueKey('playerAnchorLink'), + onPressed: () { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#4', + ); + final runtime = _runtime; + final accountIdentity = runtime.player.libraryIdentity; + _navigator.push( + MaterialPageRoute( + settings: const RouteSettings( + name: AnchorPage.routeName, + ), + builder: (_) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#4.closure#1', + ); + return AnchorPage( + runtime: runtime, + uid: anchorUid, + trackId: track.id, + initialName: artist, + accountIdentity: accountIdentity, + ); + }, + ), + ); + }, + style: TextButton.styleFrom( + minimumSize: const Size(48, 48), + padding: const EdgeInsets.symmetric(vertical: 8), + alignment: widePlayer + ? Alignment.center + : Alignment.centerLeft, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + ExcludeSemantics( + child: ClipOval( + child: CoverImage( + uri: creatorAlbum?.anchorAvatarUrl, + size: 28, + ), + ), + ), + const SizedBox(width: 8), + Flexible( + child: Text( + artist, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall, + ), + ), + ], + ), + ), + ), + ], + ], + ); + final quickControls = Wrap( + alignment: WrapAlignment.center, + spacing: 4, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + PlaybackModeButton(runtime: _runtime), + PlaybackSpeedControl( + key: ValueKey((_runtime, track?.id)), + runtime: _runtime, + albumId: track?.albumId.isNotEmpty == true + ? track!.albumId + : null, + ), + PlaybackVolumeControl(runtime: _runtime, vertical: true), + PlaybackSkipButton(runtime: _runtime, onPressed: _skipSegments), + PlaybackActionButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#5", + ); + showSleepTimerDialog(context, _runtime); + }, + icon: Icon( + sleep == null ? Icons.timer_outlined : Icons.timer, + size: 20, + ), + label: '定时关闭', + tooltip: sleepLabel, + ), + ], + ); + final contentActions = Wrap( + alignment: WrapAlignment.center, + spacing: 4, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _likeControl(track), + _favoriteControl(track), + PlaybackActionButton( + onPressed: track == null || _busy || _cancelling + ? null + : () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#6", + ); + _act(() async { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#6.closure#1", + ); + + final savedPosition = player.position; + await player.bookmark(); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + '已添加书签 · ${playbackTime(savedPosition)}', + ), + ), + ); + } + }); + }, + icon: const Icon(Icons.bookmark_add_outlined, size: 20), + label: '书签', + ), + PlaybackActionButton( + onPressed: _queue, + icon: const Icon(Icons.queue_music_rounded, size: 20), + label: '播放列表', + ), + ], + ); + final progress = Column( + children: [ + Row( + children: [ + _button( + '快退', + Icons.replay_rounded, + track == null ? null : player.seekBackward, + tooltip: _keyHint( + '后退 ${settings.seekBackwardSeconds} 秒', + '←', + ), + ), + Expanded(child: seekSlider()), + _button( + '快进', + Icons.forward_rounded, + track == null ? null : player.seekForward, + tooltip: _keyHint('前进 ${settings.seekForwardSeconds} 秒', '→'), + ), + ], + ), + DefaultTextStyle( + style: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: colors.onSurfaceVariant, + fontFeatures: const [FontFeature.tabularFigures()], + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(playbackTime(position)), + Text(playbackTime(max)), + ], + ), + ), + ], + ); + final controls = Padding( + padding: EdgeInsets.symmetric( + vertical: compact + ? 8 + : widePlayer + ? 12 + : 20, + ), + child: Wrap( + alignment: WrapAlignment.center, + spacing: 4, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _button( + '上一集', + Icons.skip_previous_rounded, + track == null ? null : player.previous, + iconSize: 30, + ), + playControl( + key: const ValueKey('playerPlayPause'), + size: 64, + coverBackground: compact, + ), + _button( + '下一集', + Icons.skip_next_rounded, + track == null ? null : player.next, + iconSize: 30, + ), + ], + ), + ); + final footer = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (sleep != null) + Center( + child: PlaybackActionButton( + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#7", + ); + + player.cancelSleep(); + _runtime.changed(); + }, + icon: const Icon(Icons.timer_off_outlined, size: 20), + label: '取消定时', + ), + ), + if (message != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + message, + key: const ValueKey('playerMessage'), + style: theme.textTheme.bodySmall?.copyWith( + color: colors.error, + ), + textAlign: TextAlign.center, + ), + ), + ], + ); + final page = Scaffold( + appBar: AppHeader( + leading: IconButton( + tooltip: '收起播放器', + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#8", + ); + Navigator.of(context).maybePop(); + }, + icon: const Icon(Icons.keyboard_arrow_down_rounded), + ), + title: const Text('正在收听'), + centerTitle: true, + actions: [ + IconButton( + tooltip: '播放设置', + onPressed: _settings, + icon: const Icon(Icons.settings_outlined), + ), + ], + ), + body: SafeArea( + top: false, + child: Column( + children: [ + AppTabStrip( + key: const ValueKey('playerContentTabs'), + children: [ + for (final (index, label) in [ + if (_paneCount == 1) (0, '播放'), + if (_hasManuscript) (1, '文稿'), + (2, '评论'), + (3, '播放列表'), + ]) + AppTabButton( + key: ValueKey(index), + label: label, + selected: + (_paneCount == 2 + ? _secondaryPage + : _selectedPage) == + index, + onPressed: () { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#9", + ); + _selectPage(index); + }, + ), + ], + ), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10", + ); + final minPaneWidth = math.max( + 460.0, + MediaQuery.textScalerOf(context).scale(340), + ); + _configurePanes( + (constraints.maxWidth / minPaneWidth).floor().clamp( + 1, + 2, + ), + ); + final order = _pageOrder; + final contents = [ + LayoutBuilder( + builder: (context, constraints) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#1", + ); + final textHeight = MediaQuery.textScalerOf(context) + .scale(56); + final coverSize = math.min( + widePlayer ? 260.0 : 280.0, + math.min( + constraints.maxWidth - 64, + math.max( + 120.0, + constraints.maxHeight - + 480 - + textHeight - + (sleep == null ? 0 : 48), + ), + ), + ); + return SingleChildScrollView( + key: const PageStorageKey('playerPlayback'), + primary: false, + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: widePlayer ? 560 : 680, + minHeight: constraints.maxHeight, + ), + child: Padding( + padding: EdgeInsets.all(compact ? 8 : 16), + child: Column( + mainAxisAlignment: + MainAxisAlignment.spaceEvenly, + children: [ + metadata, + const SizedBox(height: 8), + if (!compact) ...[ + _cover(coverUrl, coverSize), + const SizedBox(height: 8), + ], + controls, + progress, + contentActions, + quickControls, + footer, + ], + ), + ), + ), + ), + ); + }, + ), + !_visitedPages.contains(1) + ? const Center(child: CircularProgressIndicator()) + : _manuscriptPage(track), + !_visitedPages.contains(2) + ? const Center(child: CircularProgressIndicator()) + : track == null + ? const Center(child: Text('尚未选择声音')) + : TrackCommentsPanel( + key: ValueKey((_runtime, track.id)), + runtime: _runtime, + track: track, + ), + !_visitedPages.contains(3) + ? const SizedBox.shrink() + : PlayerQueuePanel( + key: ValueKey(_runtime.player), + runtime: _runtime, + ), + ]; + return PrimaryScrollController.none( + child: ScrollConfiguration( + behavior: ScrollConfiguration.of(context).copyWith( + dragDevices: { + ...ScrollConfiguration.of(context).dragDevices, + PointerDeviceKind.mouse, + }, + ), + child: PageView.builder( + controller: _pages, + padEnds: false, + physics: _paneCount == 1 + ? null + : const NeverScrollableScrollPhysics(), + onPageChanged: _pageSwiped, + itemCount: order.length, + findChildIndexCallback: (key) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#2", + ); + final index = order.indexOf( + (key as ValueKey).value, + ); + return index < 0 ? null : index; + }, + itemBuilder: (context, index) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerPanelState.build.closure#1.closure#10.closure#3", + ); + final page = order[index]; + return _PlayerPage( + key: ValueKey(page), + visible: _paneCount == 2 + ? page == 0 || page == _secondaryPage + : page == _selectedPage, + child: DecoratedBox( + decoration: BoxDecoration( + border: _paneCount == 1 + ? null + : Border( + right: BorderSide( + color: colors.outlineVariant, + ), + ), + ), + child: contents[page], + ), + ); + }, + ), + ), + ); + }, + ), + ), + ], + ), + ), + ); + return _withKeyboard(page); + }, + ); + } +} + +class _PlayerPage extends StatefulWidget { + const _PlayerPage({required this.child, required this.visible, super.key}); + + final Widget child; + final bool visible; + + @override + State<_PlayerPage> createState() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPage.createState', + ); + return _PlayerPageState(); + } +} + +class _PlayerPageState extends State<_PlayerPage> + with AutomaticKeepAliveClientMixin { + Widget? _retainedChild; + @override + bool get wantKeepAlive { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPageState.wantKeepAlive.get', + ); + return true; + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_PlayerPageState.build', + ); + super.build(context); + if (widget.visible) _retainedChild = widget.child; + return _retainedChild ?? widget.child; + } +} + +class _PlayerExpandTarget extends StatefulWidget { + const _PlayerExpandTarget({required this.onTap, required this.child}); + + final VoidCallback onTap; + final Widget child; + + @override + State<_PlayerExpandTarget> createState() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerExpandTarget.createState", + ); + return _PlayerExpandTargetState(); + } +} + +class _PlayerExpandTargetState extends State<_PlayerExpandTarget> { + final _states = WidgetStatesController(); + + @override + void dispose() { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerExpandTargetState.dispose", + ); + + _states.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerExpandTargetState.build", + ); + return ListenableBuilder( + listenable: _states, + builder: (context, _) { + AppLog.instance.trace( + "lib/pages/player_panel.dart::_PlayerExpandTargetState.build.closure#1", + ); + + final radius = BorderRadius.circular(10); + return InkWell( + onTap: widget.onTap, + statesController: _states, + mouseCursor: SystemMouseCursors.click, + borderRadius: radius, + overlayColor: const WidgetStatePropertyAll(Colors.transparent), + splashFactory: NoSplash.splashFactory, + child: DecoratedBox( + decoration: BoxDecoration( + borderRadius: radius, + border: Border.all( + width: 1.5, + color: _states.value.contains(WidgetState.focused) + ? Theme.of(context).colorScheme.primary + : Colors.transparent, + ), + ), + child: widget.child, + ), + ); + }, + ); + } +} + +class _RotatingPlayerCover extends StatefulWidget { + const _RotatingPlayerCover({ + required this.playing, + required this.child, + super.key, + }); + + final bool playing; + final Widget child; + + @override + State<_RotatingPlayerCover> createState() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_RotatingPlayerCover.createState', + ); + return _RotatingPlayerCoverState(); + } +} + +class _RotatingPlayerCoverState extends State<_RotatingPlayerCover> + with SingleTickerProviderStateMixin { + late final _rotation = AnimationController( + vsync: this, + duration: const Duration(seconds: 20), + ); + + @override + void initState() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.initState', + ); + super.initState(); + if (widget.playing) _rotation.repeat(); + } + + @override + void didUpdateWidget(covariant _RotatingPlayerCover oldWidget) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.didUpdateWidget', + ); + super.didUpdateWidget(oldWidget); + if (widget.playing == oldWidget.playing) return; + if (widget.playing) { + _rotation.repeat(); + } else { + _rotation.stop(); + } + } + + @override + void dispose() { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.dispose', + ); + _rotation.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + 'lib/pages/player_panel.dart::_RotatingPlayerCoverState.build', + ); + return RotationTransition(turns: _rotation, child: widget.child); + } +} diff --git a/lib/pages/startup_page.dart b/lib/pages/startup_page.dart index 4aacf75..25442d7 100644 --- a/lib/pages/startup_page.dart +++ b/lib/pages/startup_page.dart @@ -1,334 +1,333 @@ -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; -import 'package:path_provider/path_provider.dart'; -import 'package:sentry_flutter/sentry_flutter.dart'; - -import '../common/widgets/app_header.dart'; -import '../app.dart'; -import '../common/theme.dart'; -import '../common/widgets/log_upload_prompt_host.dart'; -import '../storage/app_storage.dart'; -import '../storage/flutter_credential_store.dart'; -import '../services/app_runtime.dart'; -import '../services/account_service.dart'; -import '../services/app_log.dart'; -import '../services/startup_directory.dart'; - -class StartupPage extends StatefulWidget { - const StartupPage({required this.arguments, super.key}); - final List arguments; - - @override - State createState() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::StartupPage.createState", - ); - return _StartupPageState(); - } -} - -class _StartupPageState extends State { - final _navigator = GlobalKey(); - final _promptRoutes = LogUploadPromptObserver(); - final _sentryRoutes = SentryNavigatorObserver(); - AppRuntime? _runtime; - String? _directory; - String? _error; - bool _opening = false; - ThemeMode _themeMode = ThemeMode.system; - Color _seedColor = const Color(AppAppearance.defaultSeedColor); - double _textScale = 1; - bool _oledBlack = false; - - @override - void initState() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.initState", - ); - - super.initState(); - _open(); - } - - Future _open([String? selected]) { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1", - ); - - if (_opening) return; - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#1", - ); - - _opening = true; - _error = null; - }); - AppStorage? candidate; - var invalidDirectoryArgument = false; - try { - if (selected != null) _directory = selected; - if (_directory == null) { - try { - _directory = startupDataDirectory(widget.arguments); - } on FormatException { - invalidDirectoryArgument = true; - rethrow; - } - _directory ??= (await getApplicationSupportDirectory()).path; - } - candidate = await AppStorage.open(_directory!); - AppRuntime.applyLogSettings(candidate.state['settings'] as Map); - // Validate persisted presentation values before leaving recovery UI. - final appearance = AppAppearance(candidate); - if (mounted) { - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#2", - ); - - _themeMode = appearance.themeMode; - _seedColor = appearance.seedColor; - _textScale = appearance.textScale; - _oledBlack = appearance.oledBlack; - }); - } - appearance.dispose(); - final runtime = AppRuntime( - storage: candidate, - secrets: FlutterCredentialStore(), - ); - await runtime.load(); - if (!mounted) { - await candidate.close(); - return; - } - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#3", - ); - - _runtime = runtime; - }); - } catch (error, stackTrace) { - AppLog.instance.level = AppLogLevel.info; - final expected = - (error is StorageException && - const {'directory', 'locked'}.contains(error.code)) || - invalidDirectoryArgument; - if (!expected) { - if (!AppLog.instance.errorWasRecorded(error)) { - AppLog.instance.write( - AppLogLevel.error, - 'startup', - '无法打开资料目录', - error: error, - stackTrace: stackTrace, - promptUser: true, - ); - } - AppLog.instance.requestUploadPrompt(); - } - try { - await candidate?.close(); - } catch (cleanupError, cleanupStack) { - AppLog.instance.write( - AppLogLevel.warning, - 'startup', - '启动失败后的资料清理未完成', - error: cleanupError, - stackTrace: cleanupStack, - promptUser: false, - ); - } finally { - await AppLog.instance.flush(); - } - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#4", - ); - - _error = - error is StorageException || - error is FormatException || - error is AccountException - ? error.toString() - : '无法打开资料目录,请检查目录权限后重试'; - }); - } finally { - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#5", - ); - - _opening = false; - }); - } - }); - } - - Future _choose() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._choose", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._choose.closure#1", - ); - - try { - final value = await FilePicker.getDirectoryPath(dialogTitle: '选择资料目录'); - if (value != null && mounted) await _open(value); - } catch (error, stack) { - if (!AppLog.instance.errorWasRecorded(error)) { - AppLog.instance.write( - AppLogLevel.error, - 'startup', - 'Choosing profile directory failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - } - if (mounted) - setState(() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState._choose.closure#1.closure#1", - ); - _error = '无法选择资料目录,请重试'; - }); - } - }); - } - - @override - void dispose() { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.dispose", - ); - - _promptRoutes.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build", - ); - - if (_runtime case final runtime?) return MyApp(runtime: runtime); - return MaterialApp( - debugShowCheckedModeBanner: false, - title: 'XMPlus', - navigatorKey: _navigator, - navigatorObservers: [_promptRoutes, _sentryRoutes], - initialRoute: '/startup/recovery', - theme: getThemeData( - seedColor: _seedColor, - brightness: Brightness.light, - oledBlack: _oledBlack, - ), - darkTheme: getThemeData( - seedColor: _seedColor, - brightness: Brightness.dark, - oledBlack: _oledBlack, - ), - themeMode: _themeMode, - builder: (context, child) { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build.closure#1", - ); - return MediaQuery( - data: MediaQuery.of(context).copyWith( - textScaler: AppTextScaler( - MediaQuery.textScalerOf(context), - _textScale, - ), - ), - child: ListenableBuilder( - listenable: _promptRoutes, - builder: (context, _) { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build.closure#1.closure#1", - ); - return LogUploadPromptHost( - navigatorKey: _navigator, - canShow: () { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build.closure#1.closure#1.closure#1", - ); - return !_opening && _error != null && !_promptRoutes.hasPopup; - }, - exportCurrent: true, - child: child!, - ); - }, - ), - ); - }, - routes: { - '/startup/recovery': (_) { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build.closure#2", - ); - return Scaffold( - appBar: usesWindowHeader - ? const AppHeader(title: Text('XMPlus'), showBrand: true) - : null, - body: SafeArea( - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 560), - child: SingleChildScrollView( - padding: const EdgeInsets.all(24), - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - if (_opening) const CircularProgressIndicator(), - if (_error != null) ...[ - Text(_error!, textAlign: TextAlign.center), - const SizedBox(height: 16), - if (_directory != null) SelectableText(_directory!), - const SizedBox(height: 16), - Wrap( - spacing: 12, - runSpacing: 12, - alignment: WrapAlignment.center, - children: [ - FilledButton( - onPressed: _opening - ? null - : () { - AppLog.instance.trace( - "lib/pages/startup_page.dart::_StartupPageState.build.closure#2.closure#1", - ); - _open(); - }, - child: const Text('重试'), - ), - OutlinedButton( - onPressed: _opening ? null : _choose, - child: const Text('选择其他资料目录'), - ), - ], - ), - ], - ], - ), - ), - ), - ), - ), - ); - }, - }, - ); - } -} +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:sentry_flutter/sentry_flutter.dart'; + +import '../common/widgets/app_header.dart'; +import '../app.dart'; +import '../common/theme.dart'; +import '../common/widgets/log_upload_prompt_host.dart'; +import '../storage/app_storage.dart'; +import '../storage/flutter_credential_store.dart'; +import '../services/app_runtime.dart'; +import '../services/account_service.dart'; +import '../services/app_log.dart'; +import '../services/startup_directory.dart'; + +class StartupPage extends StatefulWidget { + const StartupPage({required this.arguments, super.key}); + final List arguments; + + @override + State createState() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::StartupPage.createState", + ); + return _StartupPageState(); + } +} + +class _StartupPageState extends State { + final _navigator = GlobalKey(); + final _promptRoutes = LogUploadPromptObserver(); + final _sentryRoutes = SentryNavigatorObserver(); + AppRuntime? _runtime; + String? _directory; + String? _error; + bool _opening = false; + ThemeMode _themeMode = ThemeMode.system; + Color _seedColor = const Color(AppAppearance.defaultSeedColor); + double _textScale = 1; + bool _oledBlack = false; + + @override + void initState() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.initState", + ); + + super.initState(); + _open(); + } + + Future _open([String? selected]) { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1", + ); + + if (_opening) return; + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#1", + ); + + _opening = true; + _error = null; + }); + AppStorage? candidate; + var invalidDirectoryArgument = false; + try { + if (selected != null) _directory = selected; + if (_directory == null) { + try { + _directory = startupDataDirectory(widget.arguments); + } on FormatException { + invalidDirectoryArgument = true; + rethrow; + } + _directory ??= (await getApplicationSupportDirectory()).path; + } + candidate = await AppStorage.open(_directory!); + AppRuntime.applyLogSettings(candidate.state['settings'] as Map); + // Validate persisted presentation values before leaving recovery UI. + final appearance = AppAppearance(candidate); + if (mounted) { + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#2", + ); + + _themeMode = appearance.themeMode; + _seedColor = appearance.seedColor; + _textScale = appearance.textScale; + _oledBlack = appearance.oledBlack; + }); + } + appearance.dispose(); + final runtime = AppRuntime( + storage: candidate, + secrets: FlutterCredentialStore(), + ); + await runtime.load(); + if (!mounted) { + await candidate.close(); + return; + } + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#3", + ); + + _runtime = runtime; + }); + } catch (error, stackTrace) { + final expected = + (error is StorageException && + const {'directory', 'locked'}.contains(error.code)) || + invalidDirectoryArgument; + if (!expected) { + if (!AppLog.instance.errorWasRecorded(error)) { + AppLog.instance.write( + AppLogLevel.error, + 'startup', + '无法打开资料目录', + error: error, + stackTrace: stackTrace, + promptUser: true, + ); + } + AppLog.instance.requestUploadPrompt(); + } + try { + await candidate?.close(); + } catch (cleanupError, cleanupStack) { + AppLog.instance.write( + AppLogLevel.warning, + 'startup', + '启动失败后的资料清理未完成', + error: cleanupError, + stackTrace: cleanupStack, + promptUser: false, + ); + } finally { + await AppLog.instance.flush(); + } + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#4", + ); + + _error = + error is StorageException || + error is FormatException || + error is AccountException + ? error.toString() + : '无法打开资料目录,请检查目录权限后重试'; + }); + } finally { + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._open.closure#1.closure#5", + ); + + _opening = false; + }); + } + }); + } + + Future _choose() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._choose", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._choose.closure#1", + ); + + try { + final value = await FilePicker.getDirectoryPath(dialogTitle: '选择资料目录'); + if (value != null && mounted) await _open(value); + } catch (error, stack) { + if (!AppLog.instance.errorWasRecorded(error)) { + AppLog.instance.write( + AppLogLevel.error, + 'startup', + 'Choosing profile directory failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + } + if (mounted) + setState(() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState._choose.closure#1.closure#1", + ); + _error = '无法选择资料目录,请重试'; + }); + } + }); + } + + @override + void dispose() { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.dispose", + ); + + _promptRoutes.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build", + ); + + if (_runtime case final runtime?) return MyApp(runtime: runtime); + return MaterialApp( + debugShowCheckedModeBanner: false, + title: 'XMPlus', + navigatorKey: _navigator, + navigatorObservers: [_promptRoutes, _sentryRoutes], + initialRoute: '/startup/recovery', + theme: getThemeData( + seedColor: _seedColor, + brightness: Brightness.light, + oledBlack: _oledBlack, + ), + darkTheme: getThemeData( + seedColor: _seedColor, + brightness: Brightness.dark, + oledBlack: _oledBlack, + ), + themeMode: _themeMode, + builder: (context, child) { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build.closure#1", + ); + return MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: AppTextScaler( + MediaQuery.textScalerOf(context), + _textScale, + ), + ), + child: ListenableBuilder( + listenable: _promptRoutes, + builder: (context, _) { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build.closure#1.closure#1", + ); + return LogUploadPromptHost( + navigatorKey: _navigator, + canShow: () { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build.closure#1.closure#1.closure#1", + ); + return !_opening && _error != null && !_promptRoutes.hasPopup; + }, + exportCurrent: true, + child: child!, + ); + }, + ), + ); + }, + routes: { + '/startup/recovery': (_) { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build.closure#2", + ); + return Scaffold( + appBar: usesWindowHeader + ? const AppHeader(title: Text('XMPlus'), showBrand: true) + : null, + body: SafeArea( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 560), + child: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_opening) const CircularProgressIndicator(), + if (_error != null) ...[ + Text(_error!, textAlign: TextAlign.center), + const SizedBox(height: 16), + if (_directory != null) SelectableText(_directory!), + const SizedBox(height: 16), + Wrap( + spacing: 12, + runSpacing: 12, + alignment: WrapAlignment.center, + children: [ + FilledButton( + onPressed: _opening + ? null + : () { + AppLog.instance.trace( + "lib/pages/startup_page.dart::_StartupPageState.build.closure#2.closure#1", + ); + _open(); + }, + child: const Text('重试'), + ), + OutlinedButton( + onPressed: _opening ? null : _choose, + child: const Text('选择其他资料目录'), + ), + ], + ), + ], + ], + ), + ), + ), + ), + ), + ); + }, + }, + ); + } +} diff --git a/lib/services/app_log.dart b/lib/services/app_log.dart index 2545a70..1d0e2a1 100644 --- a/lib/services/app_log.dart +++ b/lib/services/app_log.dart @@ -1,1424 +1,1422 @@ -import 'dart:async'; -import 'dart:collection'; -import 'dart:convert'; -import 'dart:io'; -import 'dart:typed_data'; - -import 'package:path/path.dart' as p; -import 'package:path_provider/path_provider.dart'; -import 'package:uuid/uuid.dart'; - -enum AppLogLevel { debug, info, warning, error, fatal } - -/// This file deliberately has no method traces: logging must not log itself. -class AppLog { - AppLog({ - required Directory directory, - required String sessionId, - required DateTime startedAt, - int? processId, - }) : _root = directory, - _sessionId = sessionId, - _startedAt = startedAt.toUtc(), - _processId = processId ?? pid; - - AppLog._(); - static final instance = AppLog._(); - static const retainedBytesLimit = 1024 * 1024; - static const batchBytes = 64 * 1024; - static const fileBytesLimit = 8 * 1024 * 1024; - static const fileTailBytes = 4 * 1024 * 1024; - static const recordBytesLimit = 256 * 1024; - static const cookieReplacement = '[REDACTED COOKIE]'; - static final _ownedName = RegExp( - r'^XMPlus-(\d+)-(\d+)-([A-Za-z0-9_-]+)\.log$', - ); - static final _safeId = RegExp(r'^[A-Za-z0-9_-]+$'); - static final _exportName = RegExp(r'^XMPlus-export-[A-Za-z0-9_-]+\.log$'); - static final _activeTemporaryFiles = {}; - - Directory? _root; - String? _sessionId; - DateTime? _startedAt; - int? _processId; - String? _fileName; - File? _file; - bool _initialized = false, _closed = false, _inside = false; - bool _automaticFlushQueued = false, _promptClaimed = false; - bool _bootstrap = false; - bool _prepared = false, _urgentFlush = false; - String? _initialTrace; - Future? _initializing; - Future _work = Future.value(); - Timer? _timer; - final _pending = ListQueue<_LogLine>(); - int _pendingBytes = 0, _sequence = 0, _committedLength = 0; - int _sequenceRebase = 0; - int _missingRecords = 0, _missingBytes = 0; - int? _missingFirstSequence, _missingLastSequence; - int _lostRecords = 0, _lostBytes = 0; - String? _persistenceError; - AppLogLevel _level = AppLogLevel.warning; - bool _pendingError = false; - bool promptLogUpload = true; - final _status = StreamController.broadcast(); - final _errors = StreamController.broadcast(); - final _errorScopeKey = Object(); - final _localOnlyKey = Object(); - int _nextErrorScopeId = 0; - - /// Receives immutable Cookie-cleaned values plus transient original error - /// identity. A throwing/async-failing telemetry sink is inert. - FutureOr Function(AppLogRecord record)? sink; - - AppLogLevel get level => _level; - set level(AppLogLevel value) { - _bootstrap = false; - _level = value; - _notify(); - } - - String? get directory => _root?.path; - String? get currentFileName => _fileName; - String? get currentFilePath => _file?.path; - String? get sessionId => _sessionId; - DateTime? get startedAt => _startedAt; - String? get persistenceError => _persistenceError; - int get retainedBytes => _pendingBytes; - int get lostRecords => _lostRecords; - int get lostBytes => _lostBytes; - bool get hasPendingErrors => _pendingError; - Stream get status => _status.stream; - Stream get pendingErrors => _errors.stream; - - static AppLogLevel parseLevel(Object? value) => AppLogLevel.values.firstWhere( - (level) => level.name == value, - orElse: () => AppLogLevel.warning, - ); - - /// Windows uses this synchronous process gate. Android supplies its native - /// process-wide claim callback; it must be called only immediately before UI. - Future claimUploadPrompt({ - Future Function()? claimProcess, - }) async { - if (!promptLogUpload || !_pendingError || _promptClaimed) return false; - _promptClaimed = true; - try { - if (claimProcess != null && !await claimProcess()) return false; - _pendingError = false; - return true; - } catch (_) { - _promptClaimed = false; - return false; - } - } - - void requestUploadPrompt() { - if (Zone.current[_localOnlyKey] == true || - _closed || - _promptClaimed || - _pendingError) - return; - _pendingError = true; - if (!_errors.isClosed) _errors.add(null); - } - - _ErrorScope? get _currentErrorScope { - var scope = Zone.current[_errorScopeKey] as _ErrorScope?; - while (scope != null && !scope.active) { - scope = scope.parent; - } - return scope; - } - - Future runWithErrorScope( - Future Function() action, { - bool localOnly = false, - }) { - final scope = _ErrorScope(++_nextErrorScopeId, _currentErrorScope); - return runZoned( - () async { - try { - return await action(); - } finally { - scope.active = false; - scope.errors?.clear(); - scope.errors = null; - } - }, - zoneValues: { - _errorScopeKey: scope, - _localOnlyKey: localOnly || Zone.current[_localOnlyKey] == true, - }, - ); - } - - bool errorWasRecorded(Object error) => - _currentErrorScope?.errors?.contains(error) ?? false; - - /// A shared producer can deliver one recorded occurrence to another active - /// consumer. This does not suppress future invocations using the same error. - void inheritRecordedError(Object error) => _currentErrorScope?.record(error); - - void linkError(Object replacement, Object original) { - final scope = _currentErrorScope; - if (scope != null && (scope.errors?.contains(original) ?? false)) { - scope.record(replacement); - } - } - - Future initialize({Directory? directory}) => - _initializing ??= _initialize(directory); - - Future _initialize(Directory? directory) async { - try { - _root = - directory ?? - _root ?? - Directory( - p.join((await getApplicationSupportDirectory()).path, 'logs'), - ); - await _readProcessSession(); - } catch (error) { - _fail(error); - } - _sessionId ??= const Uuid().v4(); - _startedAt ??= DateTime.now().toUtc(); - _processId ??= pid; - try { - if (!_safeId.hasMatch(_sessionId!)) { - throw const FormatException('Invalid log session ID'); - } - _fileName = - 'XMPlus-${_startedAt!.microsecondsSinceEpoch}-$_processId-$_sessionId.log'; - final root = _root; - if (root != null) _file = File(p.join(root.path, _fileName!)); - await _prepareFile(); - } catch (error) { - _fail(error); - } - _initialized = true; - _bootstrap = true; - _level = AppLogLevel.debug; - _timer = Timer.periodic(const Duration(seconds: 1), (_) { - if (_pending.isNotEmpty || _persistenceError != null) _scheduleFlush(); - }); - final initial = _initialTrace; - _initialTrace = null; - if (initial != null) trace(initial); - _notify(); - } - - Future _readProcessSession() async { - if (_sessionId != null) return; - final file = File(p.join(_root!.path, '.process-session.json')); - if (await FileSystemEntity.type(file.path, followLinks: false) != - FileSystemEntityType.file) - return; - // Application writes this tiny metadata file atomically, once per OS process. - if (await file.length() > 4096) - throw const FormatException('Invalid process session metadata'); - final value = jsonDecode(await file.readAsString()) as Map; - final id = value['sessionId']; - final process = value['pid']; - final start = value['startedAt']; - final date = start is int - ? DateTime.fromMicrosecondsSinceEpoch(start, isUtc: true) - : DateTime.tryParse('$start')?.toUtc(); - if (id is! String || - !_safeId.hasMatch(id) || - process is! int || - process <= 0 || - date == null) { - throw const FormatException('Invalid process session metadata'); - } - // A failed native AtomicFile update can leave the previous process record. - if (process != pid) return; - _sessionId = id; - _processId = process; - _startedAt = date; - } - - Future _checkRoot() async { - final root = _root; - if (root == null) throw const FileSystemException('日志目录尚未初始化'); - final type = await FileSystemEntity.type(root.path, followLinks: false); - if (type == FileSystemEntityType.notFound) - await root.create(recursive: true); - if (await FileSystemEntity.type(root.path, followLinks: false) != - FileSystemEntityType.directory) { - throw const FileSystemException('日志目录不可用或为链接'); - } - } - - Future _prepareFile() async { - await _checkRoot(); - await _cleanTemporaryFiles(); - final file = _file; - if (file == null) throw const FileSystemException('日志会话尚未初始化'); - final type = await FileSystemEntity.type(file.path, followLinks: false); - if (type == FileSystemEntityType.notFound) { - final sessions = await _listSessions(); - // Delete only owned, ordinary files; never follow a link, including a link - // substituted since enumeration. The current process has a single writer. - for (final session in sessions.skip(6)) { - final path = session.path; - if (path != null && - await FileSystemEntity.type(path, followLinks: false) == - FileSystemEntityType.file) { - await File(path).delete(); - } - } - await file.create(exclusive: true); - _committedLength = 0; - } else if (type == FileSystemEntityType.file) { - final handle = await file.open(mode: FileMode.append); - try { - final end = await _lastNewline(handle, await handle.length()); - _committedLength = end; - await handle.truncate(end); - if (end > 0) { - final start = await _lastNewline(handle, end - 1); - await handle.setPosition(start); - final prefix = utf8.decode( - await handle.read((end - start).clamp(0, batchBytes)), - allowMalformed: true, - ); - final match = RegExp(r'"sequence":(\d+)').firstMatch(prefix); - if (match == null) - throw const FormatException('Last log record has no sequence'); - final offset = int.parse(match.group(1)!) + 1; - if (_pending.isNotEmpty) { - final rebased = _pending - .map((line) { - final values = jsonDecode( - utf8.decode(line.bytes), - ) as Map; - values['sequence'] = line.sequence + offset; - values['sessionId'] = _sessionId; - return _LogLine( - line.sequence + offset, - Uint8List.fromList(utf8.encode('${jsonEncode(values)}\n')), - ); - }) - .toList(growable: false); - _pending.clear(); - _pending.addAll(rebased); - _pendingBytes = rebased.fold( - 0, - (sum, line) => sum + line.bytes.length, - ); - } - _sequence += offset; - _sequenceRebase += offset; - if (_missingFirstSequence != null) - _missingFirstSequence = _missingFirstSequence! + offset; - if (_missingLastSequence != null) - _missingLastSequence = _missingLastSequence! + offset; - _boundTail(); - } - } finally { - await handle.close(); - } - } else { - throw const FileSystemException('日志文件不能是链接或目录'); - } - _prepared = true; - } - - Future _cleanTemporaryFiles() async { - final root = _root!; - await for (final entity in root.list(followLinks: false)) { - final name = p.basename(entity.path); - final retention = - name.endsWith('.retention') && - _ownedName.hasMatch( - name.substring(0, name.length - '.retention'.length), - ); - if ((!_exportName.hasMatch(name) && !retention) || - _activeTemporaryFiles.contains(p.absolute(entity.path))) - continue; - if (await FileSystemEntity.type(entity.path, followLinks: false) == - FileSystemEntityType.file) { - try { - await File(entity.path).delete(); - } on FileSystemException { - // An old export can still be closing after an Android engine detaches. - // Cleanup must not prevent the new logger from starting. - } - } - } - } - - Uint8List _encodeRecord(Map values) { - final bytes = Uint8List.fromList(utf8.encode('${jsonEncode(values)}\n')); - if (bytes.length <= recordBytesLimit) return bytes; - // Keep a valid JSON record and the error identity when one response or - // message is itself larger than the buffer. Cleaning has already run. - final summary = { - 'timestamp': values['timestamp'], - 'sessionId': values['sessionId'], - 'sequence': values['sequence'], - 'level': values['level'], - 'category': _excerpt('${values['category']}', 256), - 'message': _excerpt('${values['message']}', 2048), - if (values['requestId'] != null) - 'requestId': _excerpt('${values['requestId']}', 256), - 'data': { - 'logRecordTruncated': true, - 'originalBytes': bytes.length, - 'preview': utf8.decode( - bytes.sublist(0, 16 * 1024), - allowMalformed: true, - ), - }, - if (values['error'] != null) - 'error': _excerpt('${values['error']}', 8192), - if (values['stackTrace'] != null) - 'stackTrace': _excerpt('${values['stackTrace']}', 8192), - }; - return Uint8List.fromList(utf8.encode('${jsonEncode(summary)}\n')); - } - - static String _excerpt(String value, int limit) => - value.length <= limit ? value : '${value.substring(0, limit)}…'; - - void trace(String method) { - if (_inside || _closed) return; - if (!_initialized) { - _initialTrace ??= method; - return; - } - if (_level != AppLogLevel.debug) return; - write( - AppLogLevel.debug, - 'method', - method, - data: _bootstrap ? const {'phase': 'bootstrap'} : null, - ); - } - - void write( - AppLogLevel level, - String category, - String message, { - Map? data, - Object? error, - StackTrace? stackTrace, - bool networkError = false, - bool promptUser = false, - bool localOnly = false, - String? requestId, - }) { - if (_inside || _closed) return; - localOnly = localOnly || Zone.current[_localOnlyKey] == true; - if (promptUser) requestUploadPrompt(); - if (networkError) level = AppLogLevel.error; - if (!networkError && level.index < _level.index) return; - _inside = true; - try { - final values = { - 'timestamp': DateTime.now().toUtc().toIso8601String(), - 'sessionId': _sessionId, - 'sequence': _sequence++, - 'level': level.name.toUpperCase(), - 'category': category, - 'message': message, - if (requestId != null) 'requestId': requestId, - if (data != null) 'data': data, - if (error != null) 'error': '$error', - if (stackTrace != null) 'stackTrace': '$stackTrace', - }; - final cleaned = redact(values) as Map; - final bytes = _encodeRecord(cleaned); - _pending.add(_LogLine(values['sequence'] as int, bytes)); - _pendingBytes += bytes.length; - _boundTail(); - final scope = _currentErrorScope; - if (!localOnly && - error != null && - level.index >= AppLogLevel.error.index) { - scope?.record(error); - } - final callback = sink; - if (!localOnly && callback != null && category != 'method') { - try { - final result = callback( - AppLogRecord( - level, - cleaned, - networkError: networkError, - error: error, - stackTrace: stackTrace, - errorScopeId: scope?.id, - ), - ); - if (result is Future) - unawaited(result.catchError((Object _) {})); - } catch (_) { - // Telemetry is not allowed to break logging or trigger another error. - } - } - if (level.index >= AppLogLevel.error.index) _urgentFlush = true; - if (_urgentFlush || _pendingBytes >= batchBytes) _scheduleFlush(); - } catch (failure) { - // Serialization failure is a logging failure, never a business exception. - _fail(failure); - } finally { - _inside = false; - } - } - - void _scheduleFlush() { - if (_automaticFlushQueued || !_initialized || _closed) return; - _automaticFlushQueued = true; - scheduleMicrotask(() async { - _urgentFlush = false; - try { - if (!_closed) await flush(); - } finally { - _automaticFlushQueued = false; - if (_persistenceError == null && - (_urgentFlush || _pendingBytes >= batchBytes)) { - _scheduleFlush(); - } - } - }); - } - - Future flush() { - final cutoff = _sequence - 1; - final rebase = _sequenceRebase; - return _serialize(() async { - await _flushThrough(cutoff, rebase); - }); - } - - Future _serialize(Future Function() action) { - final result = _work.then((_) => action()); - _work = result.then((_) {}, onError: (Object _, StackTrace __) {}); - return result; - } - - Future _flushThrough(int cutoff, int rebase) async { - if (!_initialized) return cutoff; - final requestedCutoff = cutoff; - cutoff += _sequenceRebase - rebase; - RandomAccessFile? handle; - File? replacement; - var replacementCreated = false, replacementActive = false; - var missingRecords = 0, missingBytes = 0; - int? missingFirstSequence, missingLastSequence; - List<_LogLine> batch = const []; - var batchCommitted = false; - try { - if (!_prepared) { - final before = _sequenceRebase; - await _prepareFile(); - cutoff += _sequenceRebase - before; - } - await _checkRoot(); - final file = _file; - if (file == null) throw const FileSystemException('日志会话尚未初始化'); - var type = await FileSystemEntity.type(file.path, followLinks: false); - if (type == FileSystemEntityType.notFound && _committedLength == 0) { - await _prepareFile(); - type = await FileSystemEntity.type(file.path, followLinks: false); - } - if (type != FileSystemEntityType.file) { - throw const FileSystemException('日志文件不可用或为链接'); - } - handle = await file.open(mode: FileMode.append); - if (await handle.length() < _committedLength) { - throw const FileSystemException('日志已提交内容丢失'); - } - await handle.truncate(_committedLength); - await handle.setPosition(_committedLength); - batch = _pending - .takeWhile((line) => line.sequence <= cutoff) - .toList(growable: false); - for (final line in batch) { - _pending.removeFirst(); - _pendingBytes -= line.bytes.length; - } - // A queued snapshot can have an older cutoff than the surviving tail. - // Defer losses after that cutoff. When they can be confirmed, use a - // genuinely missing sequence and insert the notice in sequence order; - // an IO retry can leave surviving records on both sides of a lost range. - if (_missingRecords > 0 && _missingLastSequence! <= cutoff) { - missingRecords = _missingRecords; - missingBytes = _missingBytes; - missingFirstSequence = _missingFirstSequence; - missingLastSequence = _missingLastSequence; - _missingRecords = _missingBytes = 0; - _missingFirstSequence = _missingLastSequence = null; - } - var length = _committedLength; - final warning = missingRecords > 0 - ? _lossLine(missingRecords, missingBytes, missingLastSequence!) - : null; - final incoming = - batch.fold(0, (sum, line) => sum + line.bytes.length) + - (warning?.length ?? 0); - if (length + incoming > fileBytesLimit) { - replacement = File('${file.path}.retention'); - if (await FileSystemEntity.type(replacement.path, followLinks: false) != - FileSystemEntityType.notFound) - await _cleanTemporaryFiles(); - if (await FileSystemEntity.type(replacement.path, followLinks: false) != - FileSystemEntityType.notFound) { - throw const FileSystemException('日志整理临时文件已存在'); - } - replacementActive = _activeTemporaryFiles.add( - p.absolute(replacement.path), - ); - if (!replacementActive) throw const FileSystemException('日志整理正在进行'); - await replacement.create(exclusive: true); - replacementCreated = true; - final output = await replacement.open(mode: FileMode.writeOnlyAppend); - try { - final start = await _tailStart(handle, length, fileTailBytes); - if (start == length && length > 0) { - // A legacy oversized final record may leave no complete line in - // the retained range. Preserve its sequence in a small notice. - final last = await _lastNewline(handle, length - 1); - await handle.setPosition(last); - final prefix = utf8.decode( - await handle.read((length - last).clamp(0, batchBytes)), - allowMalformed: true, - ); - final match = RegExp(r'"sequence":(\d+)').firstMatch(prefix); - if (match == null) - throw const FormatException('Last log record has no sequence'); - final notice = _retentionLine(int.parse(match.group(1)!), length); - await output.writeFrom(notice); - length = notice.length; - } else { - await _copyLogRange(handle, output, start, length); - length -= start; - } - } catch (_) { - await output.close(); - rethrow; - } - try { - await handle.close(); - } catch (_) { - await output.close(); - rethrow; - } - handle = output; - } - var warningWritten = false; - for (final line in batch) { - if (warning != null && - !warningWritten && - line.sequence > missingLastSequence!) { - await handle.writeFrom(warning); - length += warning.length; - warningWritten = true; - } - await handle.writeFrom(line.bytes); - length += line.bytes.length; - } - if (warning != null && !warningWritten) { - await handle.writeFrom(warning); - length += warning.length; - } - await handle.flush(); - if (replacement != null) { - await handle.close(); - handle = null; - if (await FileSystemEntity.type(file.path, followLinks: false) != - FileSystemEntityType.file) { - throw const FileSystemException('日志整理目标已改变'); - } - await replacement.rename(file.path); - _activeTemporaryFiles.remove(p.absolute(replacement.path)); - replacement = null; - } - _committedLength = length; - batchCommitted = true; - _persistenceError = null; - _notify(); - } catch (error) { - if (!batchCommitted) { - if (missingRecords > 0) { - _addMissing( - missingRecords, - missingBytes, - missingFirstSequence!, - missingLastSequence!, - ); - } - for (final line in batch.reversed) { - _pending.addFirst(line); - _pendingBytes += line.bytes.length; - } - } - _fail(error); - } finally { - try { - await handle?.close(); - } catch (error) { - _fail(error); - } - final temporary = replacement; - if (temporary != null) { - try { - if (replacementCreated && - await FileSystemEntity.type(temporary.path, followLinks: false) == - FileSystemEntityType.file) - await temporary.delete(); - } catch (error) { - _fail(error); - } finally { - if (replacementActive) - _activeTemporaryFiles.remove(p.absolute(temporary.path)); - } - } - } - return requestedCutoff + _sequenceRebase - rebase; - } - - Uint8List _retentionLine(int sequence, int bytes) => Uint8List.fromList( - utf8.encode( - '${jsonEncode({ - 'timestamp': DateTime.now().toUtc().toIso8601String(), - 'sessionId': _sessionId, - 'sequence': sequence, - 'level': 'WARNING', - 'category': 'logging', - 'message': '超大历史日志记录已按保留上限清理', - 'data': {'omittedBytes': bytes, 'fileBytesLimit': fileBytesLimit}, - })}\n', - ), - ); - - Uint8List _lossLine(int records, int bytes, int sequence) => - Uint8List.fromList( - utf8.encode( - '${jsonEncode({ - 'timestamp': DateTime.now().toUtc().toIso8601String(), - 'sessionId': _sessionId, - 'sequence': sequence, - 'level': 'WARNING', - 'category': 'logging', - 'message': '日志缓冲空间不足;部分较早记录未保留', - 'data': {'missingRecords': records, 'missingBytes': bytes}, - })}\n', - ), - ); - - void _boundTail() { - while (_pendingBytes > retainedBytesLimit && _pending.isNotEmpty) { - final line = _pending.removeFirst(); - _pendingBytes -= line.bytes.length; - _addMissing(1, line.bytes.length, line.sequence, line.sequence); - _lostRecords++; - _lostBytes += line.bytes.length; - } - } - - void _addMissing(int records, int bytes, int first, int last) { - _missingRecords += records; - _missingBytes += bytes; - final previousFirst = _missingFirstSequence; - final previousLast = _missingLastSequence; - _missingFirstSequence = previousFirst == null || first < previousFirst - ? first - : previousFirst; - _missingLastSequence = previousLast == null || last > previousLast - ? last - : previousLast; - } - - void _fail(Object error) { - _persistenceError = '${redact('$error')}'; - _boundTail(); - _notify(); - } - - void _notify() { - if (!_status.isClosed) _status.add(null); - } - - Future> sessions() => _serialize(() async { - List result; - try { - result = (await _listSessions()).toList(); - } catch (error) { - _fail(error); - result = []; - } - final name = currentFileName; - if (name != null) { - var length = _committedLength; - final file = _file; - if (file != null) { - try { - length = - await FileSystemEntity.type(file.path, followLinks: false) == - FileSystemEntityType.file - ? await file.length() - : 0; - } catch (error) { - _fail(error); - } - } - result = result - .where((session) => session.fileName != name) - .take(6) - .toList(); - result.add( - LogSession( - name, - file?.path, - _startedAt!, - length + _pendingBytes, - isCurrent: true, - ), - ); - result.sort((a, b) { - final time = b.startedAt.compareTo(a.startedAt); - return time == 0 ? b.fileName.compareTo(a.fileName) : time; - }); - } - return List.unmodifiable(result.take(7)); - }); - - Future> _listSessions() async { - final root = _root; - if (root == null || !await root.exists()) return []; - if (await FileSystemEntity.type(root.path, followLinks: false) != - FileSystemEntityType.directory) { - throw const FileSystemException('日志目录不能是链接'); - } - final result = []; - await for (final entity in root.list(followLinks: false)) { - final name = p.basename(entity.path); - final match = _ownedName.firstMatch(name); - if (match == null || - await FileSystemEntity.type(entity.path, followLinks: false) != - FileSystemEntityType.file) - continue; - final micros = int.tryParse(match.group(1)!); - if (micros == null) continue; - final stat = await entity.stat(); - result.add( - LogSession( - name, - entity.path, - DateTime.fromMicrosecondsSinceEpoch(micros, isUtc: true), - stat.size, - isCurrent: entity.path == _file?.path, - ), - ); - } - result.sort((a, b) { - final time = b.startedAt.compareTo(a.startedAt); - return time == 0 ? b.fileName.compareTo(a.fileName) : time; - }); - return List.unmodifiable(result); - } - - Future snapshot(String fileName) { - if (!_ownedName.hasMatch(fileName) || p.basename(fileName) != fileName) { - return Future.error( - ArgumentError.value(fileName, 'fileName', 'Not an owned log basename'), - ); - } - final cutoff = _sequence - 1; - final rebase = _sequenceRebase; - return _serialize(() async { - final current = fileName == currentFileName; - final effectiveCutoff = current - ? await _flushThrough(cutoff, rebase) - : cutoff; - final root = _root; - final file = root == null ? null : File(p.join(root.path, fileName)); - String? source; - var length = 0; - try { - final type = file == null - ? FileSystemEntityType.notFound - : await FileSystemEntity.type(file.path, followLinks: false); - if (file != null && type == FileSystemEntityType.file) { - if (current) { - length = _committedLength; - if (await file.length() < length) { - final handle = await file.open(); - try { - length = await _lastNewline(handle, await handle.length()); - } finally { - await handle.close(); - } - } - } else { - final handle = await file.open(); - try { - length = await _lastNewline(handle, await handle.length()); - } finally { - await handle.close(); - } - } - source = file.path; - } else if (!current) { - throw const FileSystemException('日志文件不可用或为链接'); - } - } catch (error) { - if (!current) rethrow; - _fail(error); - length = 0; - } - String? originalSource = file?.absolute.path; - var tail = current - ? _pending - .where((line) => line.sequence <= effectiveCutoff) - .map((line) => line.bytes) - .toList(growable: false) - : const []; - var snapshotError = current ? _persistenceError : null; - final allLossesBeforeCutoff = - current && - _missingLastSequence != null && - _missingLastSequence! <= effectiveCutoff; - final missingRecords = allLossesBeforeCutoff ? _missingRecords : 0; - final missingBytes = allLossesBeforeCutoff ? _missingBytes : 0; - var retainedTail = - current && - _missingFirstSequence != null && - _missingFirstSequence! <= effectiveCutoff; - if (source != null) { - final original = File(source); - // Keep the canonical original even when freezing fails, so exporting - // through a Windows directory alias cannot overwrite the live log. - originalSource = await original.resolveSymbolicLinks(); - try { - final frozen = await _freezeSnapshot(original, length); - source = frozen.path; - length = frozen.length; - retainedTail = retainedTail || frozen.retainedTail; - } catch (error) { - // A full/read-only log directory must not prevent exporting the - // retained evidence elsewhere. Copy a bounded tail into memory; - // never expose the mutable original as a fallback snapshot source. - snapshotError = [ - if (snapshotError != null) snapshotError, - '日志快照写入失败:${redact('$error')}', - ].join('\n'); - final budget = - retainedBytesLimit - - tail.fold(0, (sum, bytes) => sum + bytes.length); - try { - final committed = await _readLogTail(original, length, budget); - tail = [...committed, ...tail]; - } catch (readError) { - snapshotError = - '$snapshotError\n日志保留片段读取失败:${redact('$readError')}'; - } - source = null; - length = 0; - retainedTail = true; - } - } - return LogSnapshot._( - source, - length, - tail, - originalSourcePath: originalSource, - retainedTail: retainedTail, - persistenceError: snapshotError, - missingRecords: missingRecords, - missingBytes: missingBytes, - ); - }); - } - - Future<({String path, String originalPath, int length, bool retainedTail})> - _freezeSnapshot(File source, int length) async { - await _checkRoot(); - final frozen = File( - p.join(_root!.path, 'XMPlus-export-${const Uuid().v4()}.log'), - ); - RandomAccessFile? input, output; - var created = false, complete = false; - _activeTemporaryFiles.add(p.absolute(frozen.path)); - try { - final originalPath = await source.resolveSymbolicLinks(); - input = await source.open(); - if (await input.length() < length) { - throw const FileSystemException('日志快照源长度不足'); - } - final start = await _tailStart(input, length, fileBytesLimit); - await input.setPosition(start); - final prefix = utf8.decode( - await input.read((length - start).clamp(0, batchBytes)), - allowMalformed: true, - ); - final firstSequence = RegExp(r'"sequence":(\d+)').firstMatch(prefix); - final retainedTail = - start > 0 || - firstSequence != null && int.parse(firstSequence.group(1)!) > 0; - await frozen.create(exclusive: true); - created = true; - output = await frozen.open(mode: FileMode.writeOnlyAppend); - await _copyLogRange(input, output, start, length); - await output.flush(); - await output.close(); - output = null; - await input.close(); - input = null; - complete = true; - return ( - path: frozen.path, - originalPath: originalPath, - length: length - start, - retainedTail: retainedTail, - ); - } finally { - try { - await input?.close(); - } catch (_) {} - try { - await output?.close(); - } catch (_) {} - if (!complete) { - try { - if (created && - await FileSystemEntity.type(frozen.path, followLinks: false) == - FileSystemEntityType.file) - await frozen.delete(); - } finally { - _activeTemporaryFiles.remove(p.absolute(frozen.path)); - } - } - } - } - - Future close() async { - if (_closed) return; - _closed = true; - _timer?.cancel(); - await flush(); - await _status.close(); - await _errors.close(); - } - - /// Cookie-only cleaning shared by local records and telemetry hooks. JSON and - /// form text are parsed before cleaning; ordinary secret/token fields survive. - static Object? redact(Object? value) => - _redact(value, HashSet.identity()); - - static bool _cookieKey(String key) { - final lower = key.toLowerCase(); - return lower == 'cookie' || lower == 'cookie2' || lower == 'set-cookie'; - } - - static Object? _redact(Object? value, Set visiting) { - if (value == null || value is num || value is bool) return value; - if (value is String) return _cleanText(value, visiting); - if (value is Map || value is Iterable) { - if (!visiting.add(value)) return '[CYCLIC VALUE]'; - try { - if (value is Map) { - return Map.unmodifiable({ - for (final entry in value.entries) - '${entry.key}': _cookieKey('${entry.key}') - ? cookieReplacement - : _redact(entry.value, visiting), - }); - } - return List.unmodifiable( - (value as Iterable).map((item) => _redact(item, visiting)), - ); - } finally { - visiting.remove(value); - } - } - return _cleanText('$value', visiting); - } - - static String _cleanText(String text, Set visiting) { - final trimmed = text.trimLeft(); - if (trimmed.startsWith('{') || trimmed.startsWith('[')) { - try { - return jsonEncode(_redact(jsonDecode(text), visiting)); - } on FormatException { - // Not JSON: still clean header lines and embedded Cookie fields below. - } - } - // A form can contain JSON or header text in an encoded field value. Do not - // mistake a URL query for a form or alter unrelated form values. - if (!text.contains('\n') && - !RegExp(r'^[A-Za-z][A-Za-z0-9+.-]*://').hasMatch(text) && - RegExp(r'^[^=&\s]+=').hasMatch(text)) { - return text - .split('&') - .map((part) { - final split = part.indexOf('='); - if (split < 0) return part; - try { - if (_cookieKey( - Uri.decodeQueryComponent(part.substring(0, split)), - )) { - return '${part.substring(0, split + 1)}${Uri.encodeQueryComponent(cookieReplacement)}'; - } - final decoded = Uri.decodeQueryComponent( - part.substring(split + 1), - ); - final cleaned = _cleanText(decoded, visiting); - if (cleaned != decoded) { - return '${part.substring(0, split + 1)}${Uri.encodeQueryComponent(cleaned)}'; - } - } on FormatException { - /* Keep non-Cookie form values verbatim. */ - } - return part; - }) - .join('&'); - } - // Match the remainder of a header line, including exception messages that - // prefix the header with context (e.g. "HttpException: Cookie: ..."). - return _cleanJsonFragments(text).replaceAllMapped( - RegExp(r'\b(cookie2?|set-cookie)\s*:\s*[^\r\n]*', caseSensitive: false), - (match) => '${match.group(1)}: $cookieReplacement', - ); - } - - // Error excerpts need not be valid JSON. Preserve surrounding text while - // recognizing JSON string tokens, including strings escaped by outer JSON. - static String _cleanJsonFragments(String text) { - StringBuffer? output; - var copied = 0; - var cursor = 0; - while (cursor < text.length) { - final quote = text.indexOf('"', cursor); - if (quote < 0) break; - cursor = quote + 1; - var start = quote; - while (start > 0 && text.codeUnitAt(start - 1) == 92) { - start--; - } - final escapes = quote - start; - // Each enclosing JSON string turns n backslashes into 2n + 1. - if ((escapes & (escapes + 1)) != 0) continue; - final keyEnd = _fragmentStringEnd(text, quote + 1, escapes); - if (keyEnd == null) continue; - var valueStart = keyEnd; - while (valueStart < text.length && text.codeUnitAt(valueStart) <= 32) { - valueStart++; - } - if (valueStart == text.length || text.codeUnitAt(valueStart) != 58) { - continue; - } - var key = text.substring(start, keyEnd); - try { - for (var layer = escapes; layer > 0; layer = (layer - 1) ~/ 2) { - key = jsonDecode('"$key"') as String; - } - if (!_cookieKey(jsonDecode(key) as String)) continue; - } on FormatException { - continue; - } - valueStart++; - while (valueStart < text.length && text.codeUnitAt(valueStart) <= 32) { - valueStart++; - } - final delimiter = '${'\\' * escapes}"'; - var end = valueStart; - if (text.startsWith(delimiter, valueStart)) { - end = - _fragmentStringEnd(text, valueStart + delimiter.length, escapes) ?? - text.length; - } else { - var depth = 0; - while (end < text.length) { - if (text.startsWith(delimiter, end)) { - end = - _fragmentStringEnd(text, end + delimiter.length, escapes) ?? - text.length; - continue; - } - final character = text.codeUnitAt(end); - if (depth == 0 && - (character == 44 || character == 125 || character == 93)) - break; - if (character == 123 || character == 91) depth++; - if (character == 125 || character == 93) depth--; - end++; - } - while (end > valueStart && text.codeUnitAt(end - 1) <= 32) { - end--; - } - } - output ??= StringBuffer(); - output.write(text.substring(copied, valueStart)); - output.write('$delimiter$cookieReplacement$delimiter'); - copied = end; - cursor = end; - } - if (output == null) return text; - output.write(text.substring(copied)); - return output.toString(); - } - - static int? _fragmentStringEnd(String text, int start, int escapes) { - var cursor = start; - while (cursor < text.length) { - final quote = text.indexOf('"', cursor); - if (quote < 0) return null; - var slash = quote; - while (slash > start && text.codeUnitAt(slash - 1) == 92) { - slash--; - } - final slashes = quote - slash; - if (slashes >= escapes && - (slashes - escapes) % (2 * (escapes + 1)) == 0) { - return quote + 1; - } - cursor = quote + 1; - } - return null; - } -} - -class _ErrorScope { - _ErrorScope(this.id, this.parent); - - final int id; - final _ErrorScope? parent; - HashSet? errors; - bool active = true; - - void record(Object error) { - for (_ErrorScope? scope = this; scope != null; scope = scope.parent) { - if (scope.active) { - (scope.errors ??= HashSet.identity()).add(error); - } - } - } -} - -class AppLogRecord { - const AppLogRecord( - this.level, - this.values, { - required this.networkError, - this.error, - this.stackTrace, - this.errorScopeId, - }); - final AppLogLevel level; - final Map values; - final bool networkError; - - /// Transient original identity for captureException. Never persisted or - /// retained by AppLog; the reporter must apply beforeSend Cookie cleaning. - final Object? error; - final StackTrace? stackTrace; - - /// Transient invocation provenance; never included in persisted values. - final int? errorScopeId; - String? get requestId => values['requestId'] as String?; -} - -class LogSession { - const LogSession( - this.fileName, - this.path, - this.startedAt, - this.byteLength, { - required this.isCurrent, - }); - final String fileName; - final String? path; - final DateTime startedAt; - final int byteLength; - final bool isCurrent; -} - -class _LogLine { - const _LogLine(this.sequence, this.bytes); - final int sequence; - final Uint8List bytes; -} - -/// A bounded, immutable export copy. Dispose it when export or clipboard work -/// finishes, including cancellation, so retention can continue independently. -class LogSnapshot { - LogSnapshot._( - this.sourcePath, - this.length, - List tail, { - required this.originalSourcePath, - required bool retainedTail, - required this.persistenceError, - required this.missingRecords, - required this.missingBytes, - }) : _tail = List.unmodifiable(tail) { - _header = Uint8List.fromList([ - if (retainedTail) - ..._notice('日志仅包含最近保留的记录,较早记录已清理', { - 'fileBytesLimit': AppLog.fileBytesLimit, - }), - if (persistenceError != null) - ..._notice('日志写入失败,当前导出仅含保留片段', {'persistenceError': persistenceError}), - ]); - _missing = missingRecords == 0 - ? Uint8List(0) - : _notice('日志记录丢失', { - 'missingRecords': missingRecords, - 'missingBytes': missingBytes, - }); - } - static const androidClipboardLimit = 512 * 1024; - static const windowsClipboardLimit = 8 * 1024 * 1024; - final String? sourcePath; - final String? originalSourcePath; - final int length; - final String? persistenceError; - final int missingRecords, missingBytes; - final List _tail; - late final Uint8List _header, _missing; - Future? _disposing; - int get tailLength => _tail.fold(0, (sum, bytes) => sum + bytes.length); - int get totalBytes => _header.length + length + tailLength + _missing.length; - bool canCopyToClipboard({required bool android}) => - totalBytes <= (android ? androidClipboardLimit : windowsClipboardLimit); - - /// Prefix notices must precede the source on both native and Dart exporters. - /// Android can use [openSuffix] as its small cache tail and [openPrefix] as a - /// warning preamble; neither helper reads the committed file. - Uint8List get warningHeader => Uint8List.fromList(_header); - Stream> openPrefix() async* { - if (_header.isNotEmpty) yield _header.asUnmodifiableView(); - } - - Stream> openSuffix() async* { - for (final bytes in _tail) yield bytes.asUnmodifiableView(); - if (_missing.isNotEmpty) yield _missing.asUnmodifiableView(); - } - - Stream> openRead() async* { - if (_disposing != null) throw StateError('日志快照已释放'); - yield* openPrefix(); - final source = sourcePath; - if (source != null && length > 0) { - if (await FileSystemEntity.type(source, followLinks: false) != - FileSystemEntityType.file) { - throw const FileSystemException('日志快照源不可用或为链接'); - } - var read = 0; - await for (final chunk in File(source).openRead(0, length)) { - read += chunk.length; - yield chunk; - } - if (read != length) throw const FileSystemException('日志快照源长度不足'); - } - yield* openSuffix(); - } - - Future dispose() => _disposing ??= _dispose(); - - Future _dispose() async { - final source = sourcePath; - if (source == null) return; - try { - if (await FileSystemEntity.type(source, followLinks: false) == - FileSystemEntityType.file) - await File(source).delete(); - } finally { - AppLog._activeTemporaryFiles.remove(p.absolute(source)); - } - } - - Future readForClipboard({required bool android}) async { - if (!canCopyToClipboard(android: android)) { - throw StateError('日志过大,无法完整复制,请导出到文件'); - } - return utf8.decoder.bind(openRead()).join(); - } - - static Uint8List _notice( - String message, - Map data, - ) => Uint8List.fromList( - utf8.encode( - '${jsonEncode({'level': 'WARNING', 'category': 'logging', 'message': message, 'data': data})}\n', - ), - ); -} - -Future> _readLogTail(File file, int end, int limit) async { - if (limit <= 0 || end <= 0) return const []; - final input = await file.open(); - try { - if (await input.length() < end) { - throw const FileSystemException('日志快照源长度不足'); - } - final start = await _tailStart(input, end, limit); - await input.setPosition(start); - final result = []; - var remaining = end - start; - while (remaining > 0) { - final bytes = await input.read(remaining.clamp(0, AppLog.batchBytes)); - if (bytes.isEmpty) throw const FileSystemException('日志保留源长度不足'); - result.add(bytes); - remaining -= bytes.length; - } - return result; - } finally { - await input.close(); - } -} - -/// Start at a complete UTF-8/JSONL record, without reading an unbounded line. -Future _tailStart(RandomAccessFile handle, int end, int limit) async { - if (end <= limit) return 0; - final start = end - limit; - await handle.setPosition(start - 1); - if ((await handle.read(1)).single == 10) return start; - await handle.setPosition(start); - var cursor = start; - while (cursor < end) { - final bytes = await handle.read((end - cursor).clamp(0, AppLog.batchBytes)); - if (bytes.isEmpty) throw const FileSystemException('日志保留源长度不足'); - final newline = bytes.indexOf(10); - if (newline >= 0) return cursor + newline + 1; - cursor += bytes.length; - } - return end; -} - -Future _copyLogRange( - RandomAccessFile input, - RandomAccessFile output, - int start, - int end, -) async { - await input.setPosition(start); - var remaining = end - start; - while (remaining > 0) { - final bytes = await input.read(remaining.clamp(0, AppLog.batchBytes)); - if (bytes.isEmpty) throw const FileSystemException('日志快照源长度不足'); - await output.writeFrom(bytes); - remaining -= bytes.length; - } -} - -/// Find an exclusive complete-line endpoint with bounded memory, even when the -/// final line is very large. A trailing interrupted write is never exported. -Future _lastNewline(RandomAccessFile handle, int before) async { - var end = before; - while (end > 0) { - final start = (end - AppLog.batchBytes).clamp(0, end); - await handle.setPosition(start); - final bytes = await handle.read(end - start); - for (var i = bytes.length - 1; i >= 0; i--) { - if (bytes[i] == 10) return start + i + 1; - } - end = start; - } - return 0; -} +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +enum AppLogLevel { debug, info, warning, error, fatal } + +/// This file deliberately has no method traces: logging must not log itself. +class AppLog { + AppLog({ + required Directory directory, + required String sessionId, + required DateTime startedAt, + int? processId, + }) : _root = directory, + _sessionId = sessionId, + _startedAt = startedAt.toUtc(), + _processId = processId ?? pid; + + AppLog._(); + static final instance = AppLog._(); + static const retainedBytesLimit = 1024 * 1024; + static const batchBytes = 64 * 1024; + static const fileBytesLimit = 8 * 1024 * 1024; + static const fileTailBytes = 4 * 1024 * 1024; + static const recordBytesLimit = 256 * 1024; + static const cookieReplacement = '[REDACTED COOKIE]'; + static final _ownedName = RegExp( + r'^XMPlus-(\d+)-(\d+)-([A-Za-z0-9_-]+)\.log$', + ); + static final _safeId = RegExp(r'^[A-Za-z0-9_-]+$'); + static final _exportName = RegExp(r'^XMPlus-export-[A-Za-z0-9_-]+\.log$'); + static final _urlPrefix = RegExp(r'^[A-Za-z][A-Za-z0-9+.-]*://'); + static final _formPrefix = RegExp(r'^[^=&\s]+='); + static final _cookieHeader = RegExp( + r'\b(cookie2?|set-cookie)\s*:\s*[^\r\n]*', + caseSensitive: false, + ); + static final _activeTemporaryFiles = {}; + + Directory? _root; + String? _sessionId; + DateTime? _startedAt; + int? _processId; + String? _fileName; + File? _file; + bool _initialized = false, _closed = false, _inside = false; + bool _automaticFlushQueued = false, _promptClaimed = false; + bool _prepared = false, _urgentFlush = false; + String? _initialTrace; + Future? _initializing; + Future _work = Future.value(); + Timer? _timer; + final _pending = ListQueue<_LogLine>(); + int _pendingBytes = 0, _sequence = 0, _committedLength = 0; + int _sequenceRebase = 0; + int _missingRecords = 0, _missingBytes = 0; + int? _missingFirstSequence, _missingLastSequence; + int _lostRecords = 0, _lostBytes = 0; + String? _persistenceError; + // Before profile settings are available, retain milestones, not method traces. + AppLogLevel _level = AppLogLevel.info; + bool _pendingError = false; + bool promptLogUpload = true; + final _status = StreamController.broadcast(); + final _errors = StreamController.broadcast(); + final _errorScopeKey = Object(); + final _localOnlyKey = Object(); + int _nextErrorScopeId = 0; + + /// Receives immutable Cookie-cleaned values plus transient original error + /// identity. A throwing/async-failing telemetry sink is inert. + FutureOr Function(AppLogRecord record)? sink; + + AppLogLevel get level => _level; + set level(AppLogLevel value) { + _level = value; + _notify(); + } + + String? get directory => _root?.path; + String? get currentFileName => _fileName; + String? get currentFilePath => _file?.path; + String? get sessionId => _sessionId; + DateTime? get startedAt => _startedAt; + String? get persistenceError => _persistenceError; + int get retainedBytes => _pendingBytes; + int get lostRecords => _lostRecords; + int get lostBytes => _lostBytes; + bool get hasPendingErrors => _pendingError; + Stream get status => _status.stream; + Stream get pendingErrors => _errors.stream; + + static AppLogLevel parseLevel(Object? value) => AppLogLevel.values.firstWhere( + (level) => level.name == value, + orElse: () => AppLogLevel.warning, + ); + + /// Windows uses this synchronous process gate. Android supplies its native + /// process-wide claim callback; it must be called only immediately before UI. + Future claimUploadPrompt({ + Future Function()? claimProcess, + }) async { + if (!promptLogUpload || !_pendingError || _promptClaimed) return false; + _promptClaimed = true; + try { + if (claimProcess != null && !await claimProcess()) return false; + _pendingError = false; + return true; + } catch (_) { + _promptClaimed = false; + return false; + } + } + + void requestUploadPrompt() { + if (Zone.current[_localOnlyKey] == true || + _closed || + _promptClaimed || + _pendingError) + return; + _pendingError = true; + if (!_errors.isClosed) _errors.add(null); + } + + _ErrorScope? get _currentErrorScope { + var scope = Zone.current[_errorScopeKey] as _ErrorScope?; + while (scope != null && !scope.active) { + scope = scope.parent; + } + return scope; + } + + Future runWithErrorScope( + Future Function() action, { + bool localOnly = false, + }) { + final scope = _ErrorScope(++_nextErrorScopeId, _currentErrorScope); + return runZoned( + () async { + try { + return await action(); + } finally { + scope.active = false; + scope.errors?.clear(); + scope.errors = null; + } + }, + zoneValues: { + _errorScopeKey: scope, + _localOnlyKey: localOnly || Zone.current[_localOnlyKey] == true, + }, + ); + } + + bool errorWasRecorded(Object error) => + _currentErrorScope?.errors?.contains(error) ?? false; + + /// A shared producer can deliver one recorded occurrence to another active + /// consumer. This does not suppress future invocations using the same error. + void inheritRecordedError(Object error) => _currentErrorScope?.record(error); + + void linkError(Object replacement, Object original) { + final scope = _currentErrorScope; + if (scope != null && (scope.errors?.contains(original) ?? false)) { + scope.record(replacement); + } + } + + Future initialize({Directory? directory}) => + _initializing ??= _initialize(directory); + + Future _initialize(Directory? directory) async { + try { + _root = + directory ?? + _root ?? + Directory( + p.join((await getApplicationSupportDirectory()).path, 'logs'), + ); + await _readProcessSession(); + } catch (error) { + _fail(error); + } + _sessionId ??= const Uuid().v4(); + _startedAt ??= DateTime.now().toUtc(); + _processId ??= pid; + try { + if (!_safeId.hasMatch(_sessionId!)) { + throw const FormatException('Invalid log session ID'); + } + _fileName = + 'XMPlus-${_startedAt!.microsecondsSinceEpoch}-$_processId-$_sessionId.log'; + final root = _root; + if (root != null) _file = File(p.join(root.path, _fileName!)); + await _prepareFile(); + } catch (error) { + _fail(error); + } + _initialized = true; + _timer = Timer.periodic(const Duration(seconds: 1), (_) { + if (_pending.isNotEmpty || _persistenceError != null) _scheduleFlush(); + }); + final initial = _initialTrace; + _initialTrace = null; + if (initial != null) trace(initial); + _notify(); + } + + Future _readProcessSession() async { + if (_sessionId != null) return; + final file = File(p.join(_root!.path, '.process-session.json')); + if (await FileSystemEntity.type(file.path, followLinks: false) != + FileSystemEntityType.file) + return; + // Application writes this tiny metadata file atomically, once per OS process. + if (await file.length() > 4096) + throw const FormatException('Invalid process session metadata'); + final value = jsonDecode(await file.readAsString()) as Map; + final id = value['sessionId']; + final process = value['pid']; + final start = value['startedAt']; + final date = start is int + ? DateTime.fromMicrosecondsSinceEpoch(start, isUtc: true) + : DateTime.tryParse('$start')?.toUtc(); + if (id is! String || + !_safeId.hasMatch(id) || + process is! int || + process <= 0 || + date == null) { + throw const FormatException('Invalid process session metadata'); + } + // A failed native AtomicFile update can leave the previous process record. + if (process != pid) return; + _sessionId = id; + _processId = process; + _startedAt = date; + } + + Future _checkRoot() async { + final root = _root; + if (root == null) throw const FileSystemException('日志目录尚未初始化'); + final type = await FileSystemEntity.type(root.path, followLinks: false); + if (type == FileSystemEntityType.notFound) + await root.create(recursive: true); + if (await FileSystemEntity.type(root.path, followLinks: false) != + FileSystemEntityType.directory) { + throw const FileSystemException('日志目录不可用或为链接'); + } + } + + Future _prepareFile() async { + await _checkRoot(); + await _cleanTemporaryFiles(); + final file = _file; + if (file == null) throw const FileSystemException('日志会话尚未初始化'); + final type = await FileSystemEntity.type(file.path, followLinks: false); + if (type == FileSystemEntityType.notFound) { + final sessions = await _listSessions(); + // Delete only owned, ordinary files; never follow a link, including a link + // substituted since enumeration. The current process has a single writer. + for (final session in sessions.skip(6)) { + final path = session.path; + if (path != null && + await FileSystemEntity.type(path, followLinks: false) == + FileSystemEntityType.file) { + await File(path).delete(); + } + } + await file.create(exclusive: true); + _committedLength = 0; + } else if (type == FileSystemEntityType.file) { + final handle = await file.open(mode: FileMode.append); + try { + final end = await _lastNewline(handle, await handle.length()); + _committedLength = end; + await handle.truncate(end); + if (end > 0) { + final start = await _lastNewline(handle, end - 1); + await handle.setPosition(start); + final prefix = utf8.decode( + await handle.read((end - start).clamp(0, batchBytes)), + allowMalformed: true, + ); + final match = RegExp(r'"sequence":(\d+)').firstMatch(prefix); + if (match == null) + throw const FormatException('Last log record has no sequence'); + final offset = int.parse(match.group(1)!) + 1; + if (_pending.isNotEmpty) { + final rebased = _pending + .map((line) { + final values = jsonDecode( + utf8.decode(line.bytes), + ) as Map; + values['sequence'] = line.sequence + offset; + values['sessionId'] = _sessionId; + return _LogLine( + line.sequence + offset, + Uint8List.fromList(utf8.encode('${jsonEncode(values)}\n')), + ); + }) + .toList(growable: false); + _pending.clear(); + _pending.addAll(rebased); + _pendingBytes = rebased.fold( + 0, + (sum, line) => sum + line.bytes.length, + ); + } + _sequence += offset; + _sequenceRebase += offset; + if (_missingFirstSequence != null) + _missingFirstSequence = _missingFirstSequence! + offset; + if (_missingLastSequence != null) + _missingLastSequence = _missingLastSequence! + offset; + _boundTail(); + } + } finally { + await handle.close(); + } + } else { + throw const FileSystemException('日志文件不能是链接或目录'); + } + _prepared = true; + } + + Future _cleanTemporaryFiles() async { + final root = _root!; + await for (final entity in root.list(followLinks: false)) { + final name = p.basename(entity.path); + final retention = + name.endsWith('.retention') && + _ownedName.hasMatch( + name.substring(0, name.length - '.retention'.length), + ); + if ((!_exportName.hasMatch(name) && !retention) || + _activeTemporaryFiles.contains(p.absolute(entity.path))) + continue; + if (await FileSystemEntity.type(entity.path, followLinks: false) == + FileSystemEntityType.file) { + try { + await File(entity.path).delete(); + } on FileSystemException { + // An old export can still be closing after an Android engine detaches. + // Cleanup must not prevent the new logger from starting. + } + } + } + } + + Uint8List _encodeRecord(Map values) { + final bytes = Uint8List.fromList(utf8.encode('${jsonEncode(values)}\n')); + if (bytes.length <= recordBytesLimit) return bytes; + // Keep a valid JSON record and the error identity when one response or + // message is itself larger than the buffer. Cleaning has already run. + final summary = { + 'timestamp': values['timestamp'], + 'sessionId': values['sessionId'], + 'sequence': values['sequence'], + 'level': values['level'], + 'category': _excerpt('${values['category']}', 256), + 'message': _excerpt('${values['message']}', 2048), + if (values['requestId'] != null) + 'requestId': _excerpt('${values['requestId']}', 256), + 'data': { + 'logRecordTruncated': true, + 'originalBytes': bytes.length, + 'preview': utf8.decode( + bytes.sublist(0, 16 * 1024), + allowMalformed: true, + ), + }, + if (values['error'] != null) + 'error': _excerpt('${values['error']}', 8192), + if (values['stackTrace'] != null) + 'stackTrace': _excerpt('${values['stackTrace']}', 8192), + }; + return Uint8List.fromList(utf8.encode('${jsonEncode(summary)}\n')); + } + + static String _excerpt(String value, int limit) => + value.length <= limit ? value : '${value.substring(0, limit)}…'; + + void trace(String method) { + if (_inside || _closed) return; + if (!_initialized) { + _initialTrace ??= method; + return; + } + if (_level != AppLogLevel.debug) return; + write(AppLogLevel.debug, 'method', method); + } + + void write( + AppLogLevel level, + String category, + String message, { + Map? data, + Object? error, + StackTrace? stackTrace, + bool networkError = false, + bool promptUser = false, + bool localOnly = false, + String? requestId, + }) { + if (_inside || _closed) return; + localOnly = localOnly || Zone.current[_localOnlyKey] == true; + if (promptUser) requestUploadPrompt(); + if (networkError) level = AppLogLevel.error; + if (!networkError && level.index < _level.index) return; + _inside = true; + try { + final values = { + 'timestamp': DateTime.now().toUtc().toIso8601String(), + 'sessionId': _sessionId, + 'sequence': _sequence++, + 'level': level.name.toUpperCase(), + 'category': category, + 'message': message, + if (requestId != null) 'requestId': requestId, + if (data != null) 'data': data, + if (error != null) 'error': '$error', + if (stackTrace != null) 'stackTrace': '$stackTrace', + }; + final cleaned = redact(values) as Map; + final bytes = _encodeRecord(cleaned); + _pending.add(_LogLine(values['sequence'] as int, bytes)); + _pendingBytes += bytes.length; + _boundTail(); + final scope = _currentErrorScope; + if (!localOnly && + error != null && + level.index >= AppLogLevel.error.index) { + scope?.record(error); + } + final callback = sink; + if (!localOnly && callback != null && category != 'method') { + try { + final result = callback( + AppLogRecord( + level, + cleaned, + networkError: networkError, + error: error, + stackTrace: stackTrace, + errorScopeId: scope?.id, + ), + ); + if (result is Future) + unawaited(result.catchError((Object _) {})); + } catch (_) { + // Telemetry is not allowed to break logging or trigger another error. + } + } + if (level.index >= AppLogLevel.error.index) _urgentFlush = true; + if (_urgentFlush || _pendingBytes >= batchBytes) _scheduleFlush(); + } catch (failure) { + // Serialization failure is a logging failure, never a business exception. + _fail(failure); + } finally { + _inside = false; + } + } + + void _scheduleFlush() { + if (_automaticFlushQueued || !_initialized || _closed) return; + _automaticFlushQueued = true; + scheduleMicrotask(() async { + _urgentFlush = false; + try { + if (!_closed) await flush(); + } finally { + _automaticFlushQueued = false; + if (_persistenceError == null && + (_urgentFlush || _pendingBytes >= batchBytes)) { + _scheduleFlush(); + } + } + }); + } + + Future flush() { + final cutoff = _sequence - 1; + final rebase = _sequenceRebase; + return _serialize(() async { + await _flushThrough(cutoff, rebase); + }); + } + + Future _serialize(Future Function() action) { + final result = _work.then((_) => action()); + _work = result.then((_) {}, onError: (Object _, StackTrace __) {}); + return result; + } + + Future _flushThrough(int cutoff, int rebase) async { + if (!_initialized) return cutoff; + final requestedCutoff = cutoff; + cutoff += _sequenceRebase - rebase; + RandomAccessFile? handle; + File? replacement; + var replacementCreated = false, replacementActive = false; + var missingRecords = 0, missingBytes = 0; + int? missingFirstSequence, missingLastSequence; + List<_LogLine> batch = const []; + var batchCommitted = false; + try { + if (!_prepared) { + final before = _sequenceRebase; + await _prepareFile(); + cutoff += _sequenceRebase - before; + } + await _checkRoot(); + final file = _file; + if (file == null) throw const FileSystemException('日志会话尚未初始化'); + var type = await FileSystemEntity.type(file.path, followLinks: false); + if (type == FileSystemEntityType.notFound && _committedLength == 0) { + await _prepareFile(); + type = await FileSystemEntity.type(file.path, followLinks: false); + } + if (type != FileSystemEntityType.file) { + throw const FileSystemException('日志文件不可用或为链接'); + } + handle = await file.open(mode: FileMode.append); + if (await handle.length() < _committedLength) { + throw const FileSystemException('日志已提交内容丢失'); + } + await handle.truncate(_committedLength); + await handle.setPosition(_committedLength); + batch = _pending + .takeWhile((line) => line.sequence <= cutoff) + .toList(growable: false); + for (final line in batch) { + _pending.removeFirst(); + _pendingBytes -= line.bytes.length; + } + // A queued snapshot can have an older cutoff than the surviving tail. + // Defer losses after that cutoff. When they can be confirmed, use a + // genuinely missing sequence and insert the notice in sequence order; + // an IO retry can leave surviving records on both sides of a lost range. + if (_missingRecords > 0 && _missingLastSequence! <= cutoff) { + missingRecords = _missingRecords; + missingBytes = _missingBytes; + missingFirstSequence = _missingFirstSequence; + missingLastSequence = _missingLastSequence; + _missingRecords = _missingBytes = 0; + _missingFirstSequence = _missingLastSequence = null; + } + var length = _committedLength; + final warning = missingRecords > 0 + ? _lossLine(missingRecords, missingBytes, missingLastSequence!) + : null; + final incoming = + batch.fold(0, (sum, line) => sum + line.bytes.length) + + (warning?.length ?? 0); + if (length + incoming > fileBytesLimit) { + replacement = File('${file.path}.retention'); + if (await FileSystemEntity.type(replacement.path, followLinks: false) != + FileSystemEntityType.notFound) + await _cleanTemporaryFiles(); + if (await FileSystemEntity.type(replacement.path, followLinks: false) != + FileSystemEntityType.notFound) { + throw const FileSystemException('日志整理临时文件已存在'); + } + replacementActive = _activeTemporaryFiles.add( + p.absolute(replacement.path), + ); + if (!replacementActive) throw const FileSystemException('日志整理正在进行'); + await replacement.create(exclusive: true); + replacementCreated = true; + final output = await replacement.open(mode: FileMode.writeOnlyAppend); + try { + final start = await _tailStart(handle, length, fileTailBytes); + if (start == length && length > 0) { + // A legacy oversized final record may leave no complete line in + // the retained range. Preserve its sequence in a small notice. + final last = await _lastNewline(handle, length - 1); + await handle.setPosition(last); + final prefix = utf8.decode( + await handle.read((length - last).clamp(0, batchBytes)), + allowMalformed: true, + ); + final match = RegExp(r'"sequence":(\d+)').firstMatch(prefix); + if (match == null) + throw const FormatException('Last log record has no sequence'); + final notice = _retentionLine(int.parse(match.group(1)!), length); + await output.writeFrom(notice); + length = notice.length; + } else { + await _copyLogRange(handle, output, start, length); + length -= start; + } + } catch (_) { + await output.close(); + rethrow; + } + try { + await handle.close(); + } catch (_) { + await output.close(); + rethrow; + } + handle = output; + } + var warningWritten = false; + for (final line in batch) { + if (warning != null && + !warningWritten && + line.sequence > missingLastSequence!) { + await handle.writeFrom(warning); + length += warning.length; + warningWritten = true; + } + await handle.writeFrom(line.bytes); + length += line.bytes.length; + } + if (warning != null && !warningWritten) { + await handle.writeFrom(warning); + length += warning.length; + } + await handle.flush(); + if (replacement != null) { + await handle.close(); + handle = null; + if (await FileSystemEntity.type(file.path, followLinks: false) != + FileSystemEntityType.file) { + throw const FileSystemException('日志整理目标已改变'); + } + await replacement.rename(file.path); + _activeTemporaryFiles.remove(p.absolute(replacement.path)); + replacement = null; + } + _committedLength = length; + batchCommitted = true; + _persistenceError = null; + _notify(); + } catch (error) { + if (!batchCommitted) { + if (missingRecords > 0) { + _addMissing( + missingRecords, + missingBytes, + missingFirstSequence!, + missingLastSequence!, + ); + } + for (final line in batch.reversed) { + _pending.addFirst(line); + _pendingBytes += line.bytes.length; + } + } + _fail(error); + } finally { + try { + await handle?.close(); + } catch (error) { + _fail(error); + } + final temporary = replacement; + if (temporary != null) { + try { + if (replacementCreated && + await FileSystemEntity.type(temporary.path, followLinks: false) == + FileSystemEntityType.file) + await temporary.delete(); + } catch (error) { + _fail(error); + } finally { + if (replacementActive) + _activeTemporaryFiles.remove(p.absolute(temporary.path)); + } + } + } + return requestedCutoff + _sequenceRebase - rebase; + } + + Uint8List _retentionLine(int sequence, int bytes) => Uint8List.fromList( + utf8.encode( + '${jsonEncode({ + 'timestamp': DateTime.now().toUtc().toIso8601String(), + 'sessionId': _sessionId, + 'sequence': sequence, + 'level': 'WARNING', + 'category': 'logging', + 'message': '超大历史日志记录已按保留上限清理', + 'data': {'omittedBytes': bytes, 'fileBytesLimit': fileBytesLimit}, + })}\n', + ), + ); + + Uint8List _lossLine(int records, int bytes, int sequence) => + Uint8List.fromList( + utf8.encode( + '${jsonEncode({ + 'timestamp': DateTime.now().toUtc().toIso8601String(), + 'sessionId': _sessionId, + 'sequence': sequence, + 'level': 'WARNING', + 'category': 'logging', + 'message': '日志缓冲空间不足;部分较早记录未保留', + 'data': {'missingRecords': records, 'missingBytes': bytes}, + })}\n', + ), + ); + + void _boundTail() { + while (_pendingBytes > retainedBytesLimit && _pending.isNotEmpty) { + final line = _pending.removeFirst(); + _pendingBytes -= line.bytes.length; + _addMissing(1, line.bytes.length, line.sequence, line.sequence); + _lostRecords++; + _lostBytes += line.bytes.length; + } + } + + void _addMissing(int records, int bytes, int first, int last) { + _missingRecords += records; + _missingBytes += bytes; + final previousFirst = _missingFirstSequence; + final previousLast = _missingLastSequence; + _missingFirstSequence = previousFirst == null || first < previousFirst + ? first + : previousFirst; + _missingLastSequence = previousLast == null || last > previousLast + ? last + : previousLast; + } + + void _fail(Object error) { + _persistenceError = '${redact('$error')}'; + _boundTail(); + _notify(); + } + + void _notify() { + if (!_status.isClosed) _status.add(null); + } + + Future> sessions() => _serialize(() async { + List result; + try { + result = (await _listSessions()).toList(); + } catch (error) { + _fail(error); + result = []; + } + final name = currentFileName; + if (name != null) { + var length = _committedLength; + final file = _file; + if (file != null) { + try { + length = + await FileSystemEntity.type(file.path, followLinks: false) == + FileSystemEntityType.file + ? await file.length() + : 0; + } catch (error) { + _fail(error); + } + } + result = result + .where((session) => session.fileName != name) + .take(6) + .toList(); + result.add( + LogSession( + name, + file?.path, + _startedAt!, + length + _pendingBytes, + isCurrent: true, + ), + ); + result.sort((a, b) { + final time = b.startedAt.compareTo(a.startedAt); + return time == 0 ? b.fileName.compareTo(a.fileName) : time; + }); + } + return List.unmodifiable(result.take(7)); + }); + + Future> _listSessions() async { + final root = _root; + if (root == null || !await root.exists()) return []; + if (await FileSystemEntity.type(root.path, followLinks: false) != + FileSystemEntityType.directory) { + throw const FileSystemException('日志目录不能是链接'); + } + final result = []; + await for (final entity in root.list(followLinks: false)) { + final name = p.basename(entity.path); + final match = _ownedName.firstMatch(name); + if (match == null || + await FileSystemEntity.type(entity.path, followLinks: false) != + FileSystemEntityType.file) + continue; + final micros = int.tryParse(match.group(1)!); + if (micros == null) continue; + final stat = await entity.stat(); + result.add( + LogSession( + name, + entity.path, + DateTime.fromMicrosecondsSinceEpoch(micros, isUtc: true), + stat.size, + isCurrent: entity.path == _file?.path, + ), + ); + } + result.sort((a, b) { + final time = b.startedAt.compareTo(a.startedAt); + return time == 0 ? b.fileName.compareTo(a.fileName) : time; + }); + return List.unmodifiable(result); + } + + Future snapshot(String fileName) { + if (!_ownedName.hasMatch(fileName) || p.basename(fileName) != fileName) { + return Future.error( + ArgumentError.value(fileName, 'fileName', 'Not an owned log basename'), + ); + } + final cutoff = _sequence - 1; + final rebase = _sequenceRebase; + return _serialize(() async { + final current = fileName == currentFileName; + final effectiveCutoff = current + ? await _flushThrough(cutoff, rebase) + : cutoff; + final root = _root; + final file = root == null ? null : File(p.join(root.path, fileName)); + String? source; + var length = 0; + try { + final type = file == null + ? FileSystemEntityType.notFound + : await FileSystemEntity.type(file.path, followLinks: false); + if (file != null && type == FileSystemEntityType.file) { + if (current) { + length = _committedLength; + if (await file.length() < length) { + final handle = await file.open(); + try { + length = await _lastNewline(handle, await handle.length()); + } finally { + await handle.close(); + } + } + } else { + final handle = await file.open(); + try { + length = await _lastNewline(handle, await handle.length()); + } finally { + await handle.close(); + } + } + source = file.path; + } else if (!current) { + throw const FileSystemException('日志文件不可用或为链接'); + } + } catch (error) { + if (!current) rethrow; + _fail(error); + length = 0; + } + String? originalSource = file?.absolute.path; + var tail = current + ? _pending + .where((line) => line.sequence <= effectiveCutoff) + .map((line) => line.bytes) + .toList(growable: false) + : const []; + var snapshotError = current ? _persistenceError : null; + final allLossesBeforeCutoff = + current && + _missingLastSequence != null && + _missingLastSequence! <= effectiveCutoff; + final missingRecords = allLossesBeforeCutoff ? _missingRecords : 0; + final missingBytes = allLossesBeforeCutoff ? _missingBytes : 0; + var retainedTail = + current && + _missingFirstSequence != null && + _missingFirstSequence! <= effectiveCutoff; + if (source != null) { + final original = File(source); + // Keep the canonical original even when freezing fails, so exporting + // through a Windows directory alias cannot overwrite the live log. + originalSource = await original.resolveSymbolicLinks(); + try { + final frozen = await _freezeSnapshot(original, length); + source = frozen.path; + length = frozen.length; + retainedTail = retainedTail || frozen.retainedTail; + } catch (error) { + // A full/read-only log directory must not prevent exporting the + // retained evidence elsewhere. Copy a bounded tail into memory; + // never expose the mutable original as a fallback snapshot source. + snapshotError = [ + if (snapshotError != null) snapshotError, + '日志快照写入失败:${redact('$error')}', + ].join('\n'); + final budget = + retainedBytesLimit - + tail.fold(0, (sum, bytes) => sum + bytes.length); + try { + final committed = await _readLogTail(original, length, budget); + tail = [...committed, ...tail]; + } catch (readError) { + snapshotError = + '$snapshotError\n日志保留片段读取失败:${redact('$readError')}'; + } + source = null; + length = 0; + retainedTail = true; + } + } + return LogSnapshot._( + source, + length, + tail, + originalSourcePath: originalSource, + retainedTail: retainedTail, + persistenceError: snapshotError, + missingRecords: missingRecords, + missingBytes: missingBytes, + ); + }); + } + + Future<({String path, String originalPath, int length, bool retainedTail})> + _freezeSnapshot(File source, int length) async { + await _checkRoot(); + final frozen = File( + p.join(_root!.path, 'XMPlus-export-${const Uuid().v4()}.log'), + ); + RandomAccessFile? input, output; + var created = false, complete = false; + _activeTemporaryFiles.add(p.absolute(frozen.path)); + try { + final originalPath = await source.resolveSymbolicLinks(); + input = await source.open(); + if (await input.length() < length) { + throw const FileSystemException('日志快照源长度不足'); + } + final start = await _tailStart(input, length, fileBytesLimit); + await input.setPosition(start); + final prefix = utf8.decode( + await input.read((length - start).clamp(0, batchBytes)), + allowMalformed: true, + ); + final firstSequence = RegExp(r'"sequence":(\d+)').firstMatch(prefix); + final retainedTail = + start > 0 || + firstSequence != null && int.parse(firstSequence.group(1)!) > 0; + await frozen.create(exclusive: true); + created = true; + output = await frozen.open(mode: FileMode.writeOnlyAppend); + await _copyLogRange(input, output, start, length); + await output.flush(); + await output.close(); + output = null; + await input.close(); + input = null; + complete = true; + return ( + path: frozen.path, + originalPath: originalPath, + length: length - start, + retainedTail: retainedTail, + ); + } finally { + try { + await input?.close(); + } catch (_) {} + try { + await output?.close(); + } catch (_) {} + if (!complete) { + try { + if (created && + await FileSystemEntity.type(frozen.path, followLinks: false) == + FileSystemEntityType.file) + await frozen.delete(); + } finally { + _activeTemporaryFiles.remove(p.absolute(frozen.path)); + } + } + } + } + + Future close() async { + if (_closed) return; + _closed = true; + _timer?.cancel(); + await flush(); + await _status.close(); + await _errors.close(); + } + + /// Cookie-only cleaning shared by local records and telemetry hooks. JSON and + /// form text are parsed before cleaning; ordinary secret/token fields survive. + static Object? redact(Object? value) => + _redact(value, HashSet.identity()); + + static bool _cookieKey(String key) { + final lower = key.toLowerCase(); + return lower == 'cookie' || lower == 'cookie2' || lower == 'set-cookie'; + } + + static Object? _redact(Object? value, Set visiting) { + if (value == null || value is num || value is bool) return value; + if (value is String) return _cleanText(value, visiting); + if (value is Map || value is Iterable) { + if (!visiting.add(value)) return '[CYCLIC VALUE]'; + try { + if (value is Map) { + return Map.unmodifiable({ + for (final entry in value.entries) + '${entry.key}': _cookieKey('${entry.key}') + ? cookieReplacement + : _redact(entry.value, visiting), + }); + } + return List.unmodifiable( + (value as Iterable).map((item) => _redact(item, visiting)), + ); + } finally { + visiting.remove(value); + } + } + return _cleanText('$value', visiting); + } + + static String _cleanText(String text, Set visiting) { + final trimmed = text.trimLeft(); + if (trimmed.startsWith('{') || trimmed.startsWith('[')) { + try { + return jsonEncode(_redact(jsonDecode(text), visiting)); + } on FormatException { + // Not JSON: still clean header lines and embedded Cookie fields below. + } + } + // A form can contain JSON or header text in an encoded field value. Do not + // mistake a URL query for a form or alter unrelated form values. + if (!text.contains('\n') && + !_urlPrefix.hasMatch(text) && + _formPrefix.hasMatch(text)) { + return text + .split('&') + .map((part) { + final split = part.indexOf('='); + if (split < 0) return part; + try { + if (_cookieKey( + Uri.decodeQueryComponent(part.substring(0, split)), + )) { + return '${part.substring(0, split + 1)}${Uri.encodeQueryComponent(cookieReplacement)}'; + } + final decoded = Uri.decodeQueryComponent( + part.substring(split + 1), + ); + final cleaned = _cleanText(decoded, visiting); + if (cleaned != decoded) { + return '${part.substring(0, split + 1)}${Uri.encodeQueryComponent(cleaned)}'; + } + } on FormatException { + /* Keep non-Cookie form values verbatim. */ + } + return part; + }) + .join('&'); + } + // Match the remainder of a header line, including exception messages that + // prefix the header with context (e.g. "HttpException: Cookie: ..."). + return _cleanJsonFragments(text).replaceAllMapped( + _cookieHeader, + (match) => '${match.group(1)}: $cookieReplacement', + ); + } + + // Error excerpts need not be valid JSON. Preserve surrounding text while + // recognizing JSON string tokens, including strings escaped by outer JSON. + static String _cleanJsonFragments(String text) { + StringBuffer? output; + var copied = 0; + var cursor = 0; + while (cursor < text.length) { + final quote = text.indexOf('"', cursor); + if (quote < 0) break; + cursor = quote + 1; + var start = quote; + while (start > 0 && text.codeUnitAt(start - 1) == 92) { + start--; + } + final escapes = quote - start; + // Each enclosing JSON string turns n backslashes into 2n + 1. + if ((escapes & (escapes + 1)) != 0) continue; + final keyEnd = _fragmentStringEnd(text, quote + 1, escapes); + if (keyEnd == null) continue; + var valueStart = keyEnd; + while (valueStart < text.length && text.codeUnitAt(valueStart) <= 32) { + valueStart++; + } + if (valueStart == text.length || text.codeUnitAt(valueStart) != 58) { + continue; + } + var key = text.substring(start, keyEnd); + try { + for (var layer = escapes; layer > 0; layer = (layer - 1) ~/ 2) { + key = jsonDecode('"$key"') as String; + } + if (!_cookieKey(jsonDecode(key) as String)) continue; + } on FormatException { + continue; + } + valueStart++; + while (valueStart < text.length && text.codeUnitAt(valueStart) <= 32) { + valueStart++; + } + final delimiter = '${'\\' * escapes}"'; + var end = valueStart; + if (text.startsWith(delimiter, valueStart)) { + end = + _fragmentStringEnd(text, valueStart + delimiter.length, escapes) ?? + text.length; + } else { + var depth = 0; + while (end < text.length) { + if (text.startsWith(delimiter, end)) { + end = + _fragmentStringEnd(text, end + delimiter.length, escapes) ?? + text.length; + continue; + } + final character = text.codeUnitAt(end); + if (depth == 0 && + (character == 44 || character == 125 || character == 93)) + break; + if (character == 123 || character == 91) depth++; + if (character == 125 || character == 93) depth--; + end++; + } + while (end > valueStart && text.codeUnitAt(end - 1) <= 32) { + end--; + } + } + output ??= StringBuffer(); + output.write(text.substring(copied, valueStart)); + output.write('$delimiter$cookieReplacement$delimiter'); + copied = end; + cursor = end; + } + if (output == null) return text; + output.write(text.substring(copied)); + return output.toString(); + } + + static int? _fragmentStringEnd(String text, int start, int escapes) { + var cursor = start; + while (cursor < text.length) { + final quote = text.indexOf('"', cursor); + if (quote < 0) return null; + var slash = quote; + while (slash > start && text.codeUnitAt(slash - 1) == 92) { + slash--; + } + final slashes = quote - slash; + if (slashes >= escapes && + (slashes - escapes) % (2 * (escapes + 1)) == 0) { + return quote + 1; + } + cursor = quote + 1; + } + return null; + } +} + +class _ErrorScope { + _ErrorScope(this.id, this.parent); + + final int id; + final _ErrorScope? parent; + HashSet? errors; + bool active = true; + + void record(Object error) { + for (_ErrorScope? scope = this; scope != null; scope = scope.parent) { + if (scope.active) { + (scope.errors ??= HashSet.identity()).add(error); + } + } + } +} + +class AppLogRecord { + const AppLogRecord( + this.level, + this.values, { + required this.networkError, + this.error, + this.stackTrace, + this.errorScopeId, + }); + final AppLogLevel level; + final Map values; + final bool networkError; + + /// Transient original identity for captureException. Never persisted or + /// retained by AppLog; the reporter must apply beforeSend Cookie cleaning. + final Object? error; + final StackTrace? stackTrace; + + /// Transient invocation provenance; never included in persisted values. + final int? errorScopeId; + String? get requestId => values['requestId'] as String?; +} + +class LogSession { + const LogSession( + this.fileName, + this.path, + this.startedAt, + this.byteLength, { + required this.isCurrent, + }); + final String fileName; + final String? path; + final DateTime startedAt; + final int byteLength; + final bool isCurrent; +} + +class _LogLine { + const _LogLine(this.sequence, this.bytes); + final int sequence; + final Uint8List bytes; +} + +/// A bounded, immutable export copy. Dispose it when export or clipboard work +/// finishes, including cancellation, so retention can continue independently. +class LogSnapshot { + LogSnapshot._( + this.sourcePath, + this.length, + List tail, { + required this.originalSourcePath, + required bool retainedTail, + required this.persistenceError, + required this.missingRecords, + required this.missingBytes, + }) : _tail = List.unmodifiable(tail) { + _header = Uint8List.fromList([ + if (retainedTail) + ..._notice('日志仅包含最近保留的记录,较早记录已清理', { + 'fileBytesLimit': AppLog.fileBytesLimit, + }), + if (persistenceError != null) + ..._notice('日志写入失败,当前导出仅含保留片段', {'persistenceError': persistenceError}), + ]); + _missing = missingRecords == 0 + ? Uint8List(0) + : _notice('日志记录丢失', { + 'missingRecords': missingRecords, + 'missingBytes': missingBytes, + }); + } + static const androidClipboardLimit = 512 * 1024; + static const windowsClipboardLimit = 8 * 1024 * 1024; + final String? sourcePath; + final String? originalSourcePath; + final int length; + final String? persistenceError; + final int missingRecords, missingBytes; + final List _tail; + late final Uint8List _header, _missing; + Future? _disposing; + int get tailLength => _tail.fold(0, (sum, bytes) => sum + bytes.length); + int get totalBytes => _header.length + length + tailLength + _missing.length; + bool canCopyToClipboard({required bool android}) => + totalBytes <= (android ? androidClipboardLimit : windowsClipboardLimit); + + /// Prefix notices must precede the source on both native and Dart exporters. + /// Android can use [openSuffix] as its small cache tail and [openPrefix] as a + /// warning preamble; neither helper reads the committed file. + Uint8List get warningHeader => Uint8List.fromList(_header); + Stream> openPrefix() async* { + if (_header.isNotEmpty) yield _header.asUnmodifiableView(); + } + + Stream> openSuffix() async* { + for (final bytes in _tail) yield bytes.asUnmodifiableView(); + if (_missing.isNotEmpty) yield _missing.asUnmodifiableView(); + } + + Stream> openRead() async* { + if (_disposing != null) throw StateError('日志快照已释放'); + yield* openPrefix(); + final source = sourcePath; + if (source != null && length > 0) { + if (await FileSystemEntity.type(source, followLinks: false) != + FileSystemEntityType.file) { + throw const FileSystemException('日志快照源不可用或为链接'); + } + var read = 0; + await for (final chunk in File(source).openRead(0, length)) { + read += chunk.length; + yield chunk; + } + if (read != length) throw const FileSystemException('日志快照源长度不足'); + } + yield* openSuffix(); + } + + Future dispose() => _disposing ??= _dispose(); + + Future _dispose() async { + final source = sourcePath; + if (source == null) return; + try { + if (await FileSystemEntity.type(source, followLinks: false) == + FileSystemEntityType.file) + await File(source).delete(); + } finally { + AppLog._activeTemporaryFiles.remove(p.absolute(source)); + } + } + + Future readForClipboard({required bool android}) async { + if (!canCopyToClipboard(android: android)) { + throw StateError('日志过大,无法完整复制,请导出到文件'); + } + return utf8.decoder.bind(openRead()).join(); + } + + static Uint8List _notice( + String message, + Map data, + ) => Uint8List.fromList( + utf8.encode( + '${jsonEncode({'level': 'WARNING', 'category': 'logging', 'message': message, 'data': data})}\n', + ), + ); +} + +Future> _readLogTail(File file, int end, int limit) async { + if (limit <= 0 || end <= 0) return const []; + final input = await file.open(); + try { + if (await input.length() < end) { + throw const FileSystemException('日志快照源长度不足'); + } + final start = await _tailStart(input, end, limit); + await input.setPosition(start); + final result = []; + var remaining = end - start; + while (remaining > 0) { + final bytes = await input.read(remaining.clamp(0, AppLog.batchBytes)); + if (bytes.isEmpty) throw const FileSystemException('日志保留源长度不足'); + result.add(bytes); + remaining -= bytes.length; + } + return result; + } finally { + await input.close(); + } +} + +/// Start at a complete UTF-8/JSONL record, without reading an unbounded line. +Future _tailStart(RandomAccessFile handle, int end, int limit) async { + if (end <= limit) return 0; + final start = end - limit; + await handle.setPosition(start - 1); + if ((await handle.read(1)).single == 10) return start; + await handle.setPosition(start); + var cursor = start; + while (cursor < end) { + final bytes = await handle.read((end - cursor).clamp(0, AppLog.batchBytes)); + if (bytes.isEmpty) throw const FileSystemException('日志保留源长度不足'); + final newline = bytes.indexOf(10); + if (newline >= 0) return cursor + newline + 1; + cursor += bytes.length; + } + return end; +} + +Future _copyLogRange( + RandomAccessFile input, + RandomAccessFile output, + int start, + int end, +) async { + await input.setPosition(start); + var remaining = end - start; + while (remaining > 0) { + final bytes = await input.read(remaining.clamp(0, AppLog.batchBytes)); + if (bytes.isEmpty) throw const FileSystemException('日志快照源长度不足'); + await output.writeFrom(bytes); + remaining -= bytes.length; + } +} + +/// Find an exclusive complete-line endpoint with bounded memory, even when the +/// final line is very large. A trailing interrupted write is never exported. +Future _lastNewline(RandomAccessFile handle, int before) async { + var end = before; + while (end > 0) { + final start = (end - AppLog.batchBytes).clamp(0, end); + await handle.setPosition(start); + final bytes = await handle.read(end - start); + for (var i = bytes.length - 1; i >= 0; i--) { + if (bytes[i] == 10) return start + i + 1; + } + end = start; + } + return 0; +} diff --git a/lib/services/auto_download_service.dart b/lib/services/auto_download_service.dart index 6b99c62..791467c 100644 --- a/lib/services/auto_download_service.dart +++ b/lib/services/auto_download_service.dart @@ -1,576 +1,578 @@ -import 'dart:async'; - -import 'package:uuid/uuid.dart'; - -import '../models/xmly_models.dart'; -import '../storage/app_storage.dart'; -import 'app_log.dart'; -import 'download_service.dart' show DownloadStopped; - -/// Only explicit, local consent authorizes future downloads. The catalogue at -/// consent time is a complete baseline, never an instruction to backfill. -class AutoDownloadService { - AutoDownloadService({ - required this.storage, - required this.checkAccount, - required this.loadCatalogue, - required this.hasTask, - required this.enqueueNew, - }) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.new", - ); - } - - final AppStorage storage; - final void Function(String identity) checkAccount; - final Future> Function( - String identity, - String albumId, - Future cancelled, - Future Function() checkpoint, - ) - loadCatalogue; - final bool Function(String identity, String trackId) hasTask; - final Future Function( - String identity, - Track track, - bool Function() allowed, - Future cancelled, - ) - enqueueNew; - final _changes = StreamController.broadcast(); - final _flights = >{}; - final _revisions = {}; - final _errors = {}; - final _pendingStops = >>{}; - - Completer _startRead(String key) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._startRead", - ); - - final stop = Completer(); - _pendingStops - .putIfAbsent(key, () { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._startRead.closure#1", - ); - return {}; - }) - .add(stop); - return stop; - } - - void _stopReads([String? key]) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._stopReads", - ); - - final keys = key == null ? _pendingStops.keys.toList() : [key]; - for (final item in keys) { - for (final stop in _pendingStops.remove(item) ?? >{}) { - if (!stop.isCompleted) stop.complete(); - } - } - } - - void _finishRead(String key, Completer stop) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._finishRead", - ); - - _pendingStops[key]?.remove(stop); - if (_pendingStops[key]?.isEmpty == true) _pendingStops.remove(key); - } - - int _generation = 0; - bool _suspended = false, _closed = false; - - Stream get changes { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.changes.get", - ); - return _changes.stream; - } - - List get errors { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.errors.get", - ); - return List.unmodifiable(_errors.values); - } - - String _key(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._key", - ); - return '$identity/$albumId'; - } - - Map? _record(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._record", - ); - - final all = (storage.state['settings'] as Map)['autoDownloads']; - final albums = all is Map ? all[identity] : null; - final record = albums is Map ? albums[albumId] : null; - return record is Map ? record : null; - } - - bool enabled(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.enabled", - ); - return _record(identity, albumId)?['enabled'] == true; - } - - String? errorFor(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.errorFor", - ); - return _errors[_key(identity, albumId)]; - } - - Future setEnabled( - String identity, - String albumId, { - required bool confirmed, - }) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1", - ); - - if (_closed) return; - final key = _key(identity, albumId); - _stopReads(key); - final revision = (_revisions[key] ?? 0) + 1; - _revisions[key] = - revision; // Cancel in-flight work before the first await. - final generation = _generation; - bool current() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.current", - ); - return !_closed && - !_suspended && - _generation == generation && - _revisions[key] == revision; - } - - if (!confirmed) { - try { - await storage.transaction((state) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#1", - ); - - final all = (state['settings'] as Map)['autoDownloads']; - final albums = all is Map ? all[identity] : null; - final record = albums is Map ? albums[albumId] : null; - if (record is Map) record['enabled'] = false; - }); - } catch (error, stack) { - _recordFailure('Disabling automatic download failed', error, stack); - rethrow; - } - _errors.remove(key); - _notify(); - return; - } - final stop = _startRead(key); - Future checkpoint() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.checkpoint", - ); - - if (!current()) throw const _StaleConsent(); - checkAccount(identity); - } - - try { - if (!current()) return; - checkAccount(identity); - final tracks = _catalogue( - await loadCatalogue(identity, albumId, stop.future, checkpoint), - albumId, - ); - if (!current()) return; - checkAccount(identity); - await storage.transaction((state) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2", - ); - - if (!current()) throw const _StaleConsent(); - checkAccount(identity); - final all = (state['settings'] as Map).putIfAbsent( - 'autoDownloads', - () { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#1", - ); - return {}; - }, - ) as Map; - final albums = all.putIfAbsent(identity, () { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#2", - ); - return {}; - }) as Map; - albums[albumId] = { - 'enabled': true, - 'consentId': const Uuid().v4(), - 'seen': tracks.map((track) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#3", - ); - return track.id; - }).toList(), - 'pending': [], - }; - }); - _errors.remove(key); - } on _StaleConsent { - // Closing, disabling and restore invalidate requests without side effects. - } catch (error, stack) { - if (!current()) return; - _recordFailure('Enabling automatic download failed', error, stack); - _errors[key] = _message(error); - rethrow; - } finally { - _finishRead(key, stop); - _notify(); - } - }); - } - - Future scanAll() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.scanAll", - ); - - final generation = _generation; - final all = (storage.state['settings'] as Map)['autoDownloads']; - if (all is! Map) return; - for (final entry in all.entries) { - if (entry.key is! String || entry.value is! Map) continue; - for (final album in (entry.value as Map).keys) { - if (_closed || _suspended || generation != _generation) return; - if (album is String) await scanAlbum(entry.key as String, album); - } - } - } - - Future scanAlbum(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.scanAlbum", - ); - - if (_closed || _suspended || !enabled(identity, albumId)) - return Future.value(); - final key = _key(identity, albumId); - final existing = _flights[key]; - if (existing != null) return existing; - final future = _scan(identity, albumId).whenComplete(() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.scanAlbum.closure#1", - ); - - _flights.remove(key); - }); - _flights[key] = future; - return future; - } - - Future _scan(String identity, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1", - ); - - final key = _key(identity, albumId); - final stop = _startRead(key); - final generation = _generation, revision = _revisions[key]; - final consent = _record(identity, albumId)?['consentId']; - bool allowed() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.allowed", - ); - return !_closed && - !_suspended && - _generation == generation && - _revisions[key] == revision && - consent is String && - _record(identity, albumId)?['consentId'] == consent && - enabled(identity, albumId); - } - - Future checkpoint() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.checkpoint", - ); - - if (!allowed()) throw const _StaleConsent(); - checkAccount(identity); - } - - Future update(void Function(Map record) change) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.update", - ); - return storage.transaction((state) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.update.closure#1", - ); - - if (!allowed()) throw const _StaleConsent(); - checkAccount(identity); - final record = - ((state['settings'] as Map)['autoDownloads'] - as Map)[identity][albumId] - as Map; - change(record); - }); - } - - try { - if (consent is! String || consent.isEmpty) { - throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); - } - await checkpoint(); - final tracks = _catalogue( - await loadCatalogue(identity, albumId, stop.future, checkpoint), - albumId, - ); - await checkpoint(); - final record = _record(identity, albumId)!; - final seen = _ids(record['seen']); - final pending = _pending(record['pending'], albumId); - for (final track in tracks) { - if (!seen.contains(track.id)) pending[track.id] = track; - } - // Durably remember additions BEFORE preparing permission/quota or tasks. - await update((value) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#1", - ); - - value['pending'] = pending.values.map((track) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#1.closure#1", - ); - return track.toJson(); - }).toList(); - }); - for (final track in pending.values) { - await checkpoint(); - // Every existing state wins, including cancelled/failed/restored tasks. - if (!hasTask(identity, track.id)) { - await enqueueNew(identity, track, allowed, stop.future); - await checkpoint(); - if (!hasTask(identity, track.id)) { - throw const XmlyException('auto_not_enqueued', '新声音未加入下载列表'); - } - } - await update((value) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2", - ); - - final ids = _ids(value['seen'])..add(track.id); - value['seen'] = ids.toList(); - value['pending'] = _pending(value['pending'], albumId).values - .where((item) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2.closure#1", - ); - return item.id != track.id; - }) - .map((item) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2.closure#2", - ); - return item.toJson(); - }) - .toList(); - }); - } - _errors.remove(key); - } on _StaleConsent { - // Never advance a baseline or enqueue after consent has been invalidated. - } catch (error, stack) { - if (allowed()) { - _recordFailure('Automatic download scan failed', error, stack); - _errors[key] = _message(error); - } - } finally { - _finishRead(key, stop); - _notify(); - } - }); - } - - static Set _ids(Object? value) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._ids", - ); - - if (value is! List || - value.any((id) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._ids.closure#1", - ); - return id is! String; - })) { - throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); - } - return value.cast().toSet(); - } - - static const _invalidCatalogue = XmlyException( - 'auto_catalogue', - '专辑列表不完整,自动下载已停止', - ); - - static Map _pending(Object? value, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._pending", - ); - - if (value is! List) - throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); - final pending = {}; - for (final item in value) { - final track = Track.fromJson(Map.from(item as Map)); - if (track.albumId != albumId) throw _invalidCatalogue; - pending[track.id] = track; - } - return pending; - } - - static List _catalogue(List tracks, String albumId) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._catalogue", - ); - - final ids = {}; - if (tracks.length > 5000 || - tracks.any((track) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._catalogue.closure#1", - ); - return track.albumId != albumId || !ids.add(track.id); - })) { - throw _invalidCatalogue; - } - return tracks; - } - - static String _message(Object error) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._message", - ); - return switch (error) { - XmlyException(code: 'usage_uncertain') => '自动下载已停止:请先核对未确认的听时', - XmlyException(code: 'insufficient_quota') => '自动下载已停止:听时不足', - XmlyException(code: 'login_expired') => '自动下载已停止:请重新登录原账号', - _ => '自动下载未完成,请检查原账号、听时和下载目录后重新检查专辑', - }; - } - - void _recordFailure(String message, Object error, StackTrace stack) { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._recordFailure", - ); - - if (error is _StaleConsent || error is DownloadStopped) return; - if (error is XmlyException && - const { - 'client_closed', - 'request_cancelled', - 'closed', - 'missing_account', - 'account_mismatch', - 'task_mismatch', - 'login_required', - 'login_expired', - 'auth_required', - 'confirmation_required', - 'confirmation_changed', - 'insufficient_quota', - 'usage_uncertain', - }.contains(error.code)) - return; - if (!AppLog.instance.errorWasRecorded(error)) { - AppLog.instance.write( - AppLogLevel.error, - 'auto_download', - message, - error: error, - stackTrace: stack, - ); - } - AppLog.instance.requestUploadPrompt(); - } - - /// Cancel pending discovery/admission without removing saved subscriptions. - void invalidatePending() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.invalidatePending", - ); - - _generation++; - _stopReads(); - } - - /// Synchronous invalidation avoids waiting on account locks during restore. - void suspend() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.suspend", - ); - - invalidatePending(); - _suspended = true; - } - - void resume() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.resume", - ); - - if (!_closed) _suspended = false; - } - - void _notify() { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService._notify", - ); - - if (!_changes.isClosed) _changes.add(null); - } - - Future close() async { - AppLog.instance.trace( - "lib/services/auto_download_service.dart::AutoDownloadService.close", - ); - - _closed = true; - suspend(); - await Future.wait(_flights.values.toList()); - await _changes.close(); - } -} - -class _StaleConsent implements Exception { - const _StaleConsent(); -} +import 'dart:async'; + +import 'package:uuid/uuid.dart'; + +import '../models/xmly_models.dart'; +import '../storage/app_storage.dart'; +import 'app_log.dart'; +import 'download_service.dart' show DownloadStopped; + +/// Only explicit, local consent authorizes future downloads. The catalogue at +/// consent time is a complete baseline, never an instruction to backfill. +class AutoDownloadService { + AutoDownloadService({ + required this.storage, + required this.checkAccount, + required this.loadCatalogue, + required this.hasTask, + required this.enqueueNew, + }) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.new", + ); + } + + final AppStorage storage; + final void Function(String identity) checkAccount; + final Future> Function( + String identity, + String albumId, + Future cancelled, + Future Function() checkpoint, + ) + loadCatalogue; + final bool Function(String identity, String trackId) hasTask; + final Future Function( + String identity, + Track track, + bool Function() allowed, + Future cancelled, + ) + enqueueNew; + final _changes = StreamController.broadcast(); + final _flights = >{}; + final _revisions = {}; + final _errors = {}; + final _pendingStops = >>{}; + + Completer _startRead(String key) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._startRead", + ); + + final stop = Completer(); + _pendingStops + .putIfAbsent(key, () { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._startRead.closure#1", + ); + return {}; + }) + .add(stop); + return stop; + } + + void _stopReads([String? key]) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._stopReads", + ); + + final keys = key == null ? _pendingStops.keys.toList() : [key]; + for (final item in keys) { + for (final stop in _pendingStops.remove(item) ?? >{}) { + if (!stop.isCompleted) stop.complete(); + } + } + } + + void _finishRead(String key, Completer stop) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._finishRead", + ); + + _pendingStops[key]?.remove(stop); + if (_pendingStops[key]?.isEmpty == true) _pendingStops.remove(key); + } + + int _generation = 0; + bool _suspended = false, _closed = false; + + Stream get changes { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.changes.get", + ); + return _changes.stream; + } + + List get errors { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.errors.get", + ); + return List.unmodifiable(_errors.values); + } + + String _key(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._key", + ); + return '$identity/$albumId'; + } + + Map? _record(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._record", + ); + + final all = (storage.state['settings'] as Map)['autoDownloads']; + final albums = all is Map ? all[identity] : null; + final record = albums is Map ? albums[albumId] : null; + return record is Map ? record : null; + } + + bool enabled(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.enabled", + ); + return _record(identity, albumId)?['enabled'] == true; + } + + String? errorFor(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.errorFor", + ); + return _errors[_key(identity, albumId)]; + } + + Future setEnabled( + String identity, + String albumId, { + required bool confirmed, + }) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1", + ); + + if (_closed) return; + final key = _key(identity, albumId); + _stopReads(key); + final revision = (_revisions[key] ?? 0) + 1; + _revisions[key] = + revision; // Cancel in-flight work before the first await. + final generation = _generation; + bool current() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.current", + ); + return !_closed && + !_suspended && + _generation == generation && + _revisions[key] == revision; + } + + if (!confirmed) { + try { + await storage.transaction((state) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#1", + ); + + final all = (state['settings'] as Map)['autoDownloads']; + final albums = all is Map ? all[identity] : null; + final record = albums is Map ? albums[albumId] : null; + if (record is Map) record['enabled'] = false; + }); + } catch (error, stack) { + _recordFailure('Disabling automatic download failed', error, stack); + rethrow; + } + _errors.remove(key); + _notify(); + return; + } + final stop = _startRead(key); + Future checkpoint() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.checkpoint", + ); + + if (!current()) throw const _StaleConsent(); + checkAccount(identity); + } + + try { + if (!current()) return; + checkAccount(identity); + final tracks = _catalogue( + await loadCatalogue(identity, albumId, stop.future, checkpoint), + albumId, + ); + if (!current()) return; + checkAccount(identity); + await storage.transaction((state) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2", + ); + + if (!current()) throw const _StaleConsent(); + checkAccount(identity); + final all = (state['settings'] as Map).putIfAbsent( + 'autoDownloads', + () { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#1", + ); + return {}; + }, + ) as Map; + final albums = all.putIfAbsent(identity, () { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#2", + ); + return {}; + }) as Map; + albums[albumId] = { + 'enabled': true, + 'consentId': const Uuid().v4(), + 'seen': tracks.map((track) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.setEnabled.closure#1.closure#2.closure#3", + ); + return track.id; + }).toList(), + 'pending': [], + }; + }); + _errors.remove(key); + } on _StaleConsent { + // Closing, disabling and restore invalidate requests without side effects. + } catch (error, stack) { + if (!current()) return; + _recordFailure('Enabling automatic download failed', error, stack); + _errors[key] = _message(error); + rethrow; + } finally { + _finishRead(key, stop); + _notify(); + } + }); + } + + Future scanAll() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.scanAll", + ); + + final generation = _generation; + final all = (storage.state['settings'] as Map)['autoDownloads']; + if (all is! Map) return; + for (final entry in all.entries) { + if (entry.key is! String || entry.value is! Map) continue; + for (final album in (entry.value as Map).keys) { + if (_closed || _suspended || generation != _generation) return; + if (album is String) await scanAlbum(entry.key as String, album); + } + } + } + + Future scanAlbum(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.scanAlbum", + ); + + if (_closed || _suspended || !enabled(identity, albumId)) + return Future.value(); + final key = _key(identity, albumId); + final existing = _flights[key]; + if (existing != null) return existing; + final future = _scan(identity, albumId).whenComplete(() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.scanAlbum.closure#1", + ); + + _flights.remove(key); + }); + _flights[key] = future; + return future; + } + + Future _scan(String identity, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1", + ); + + final key = _key(identity, albumId); + final stop = _startRead(key); + final generation = _generation, revision = _revisions[key]; + final consent = _record(identity, albumId)?['consentId']; + bool allowed() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.allowed", + ); + return !_closed && + !_suspended && + _generation == generation && + _revisions[key] == revision && + consent is String && + _record(identity, albumId)?['consentId'] == consent && + enabled(identity, albumId); + } + + Future checkpoint() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.checkpoint", + ); + + if (!allowed()) throw const _StaleConsent(); + checkAccount(identity); + } + + Future update(void Function(Map record) change) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.update", + ); + return storage.transaction((state) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.update.closure#1", + ); + + if (!allowed()) throw const _StaleConsent(); + checkAccount(identity); + final record = + ((state['settings'] as Map)['autoDownloads'] + as Map)[identity][albumId] + as Map; + change(record); + }); + } + + try { + if (consent is! String || consent.isEmpty) { + throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); + } + await checkpoint(); + final tracks = _catalogue( + await loadCatalogue(identity, albumId, stop.future, checkpoint), + albumId, + ); + await checkpoint(); + final record = _record(identity, albumId)!; + final seen = _ids(record['seen']); + final pending = _pending(record['pending'], albumId); + for (final track in tracks) { + if (!seen.contains(track.id)) pending[track.id] = track; + } + // Durably remember additions BEFORE preparing permission/quota or tasks. + await update((value) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#1", + ); + + value['pending'] = pending.values.map((track) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#1.closure#1", + ); + return track.toJson(); + }).toList(); + }); + for (final track in pending.values) { + await checkpoint(); + // Every existing state wins, including cancelled/failed/restored tasks. + if (!hasTask(identity, track.id)) { + await enqueueNew(identity, track, allowed, stop.future); + await checkpoint(); + if (!hasTask(identity, track.id)) { + throw const XmlyException('auto_not_enqueued', '新声音未加入下载列表'); + } + } + await update((value) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2", + ); + + final ids = _ids(value['seen'])..add(track.id); + value['seen'] = ids.toList(); + value['pending'] = _pending(value['pending'], albumId).values + .where((item) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2.closure#1", + ); + return item.id != track.id; + }) + .map((item) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._scan.closure#1.closure#2.closure#2", + ); + return item.toJson(); + }) + .toList(); + }); + } + _errors.remove(key); + } on _StaleConsent { + // Never advance a baseline or enqueue after consent has been invalidated. + } catch (error, stack) { + if (allowed()) { + _recordFailure('Automatic download scan failed', error, stack); + _errors[key] = _message(error); + } + } finally { + _finishRead(key, stop); + _notify(); + } + }); + } + + static Set _ids(Object? value) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._ids", + ); + + if (value is! List || + value.any((id) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._ids.closure#1", + ); + return id is! String; + })) { + throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); + } + return value.cast().toSet(); + } + + static const _invalidCatalogue = XmlyException( + 'auto_catalogue', + '专辑列表不完整,自动下载已停止', + ); + + static Map _pending(Object? value, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._pending", + ); + + if (value is! List) + throw const XmlyException('auto_invalid', '自动下载资料无效,请关闭后重新开启'); + final pending = {}; + for (final item in value) { + final track = Track.fromJson(Map.from(item as Map)); + if (track.albumId != albumId) throw _invalidCatalogue; + pending[track.id] = track; + } + return pending; + } + + static List _catalogue(List tracks, String albumId) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._catalogue", + ); + + final ids = {}; + if (tracks.length > 5000 || + tracks.any((track) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._catalogue.closure#1", + ); + return track.albumId != albumId || !ids.add(track.id); + })) { + throw _invalidCatalogue; + } + return tracks; + } + + static String _message(Object error) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._message", + ); + return switch (error) { + XmlyException(code: 'content_removed') => '自动下载已停止:专辑已下架', + XmlyException(code: 'usage_uncertain') => '自动下载已停止:请先核对未确认的听时', + XmlyException(code: 'insufficient_quota') => '自动下载已停止:听时不足', + XmlyException(code: 'login_expired') => '自动下载已停止:请重新登录原账号', + _ => '自动下载未完成,请检查原账号、听时和下载目录后重新检查专辑', + }; + } + + void _recordFailure(String message, Object error, StackTrace stack) { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._recordFailure", + ); + + if (error is _StaleConsent || error is DownloadStopped) return; + if (error is XmlyException && + const { + 'client_closed', + 'request_cancelled', + 'closed', + 'missing_account', + 'account_mismatch', + 'task_mismatch', + 'login_required', + 'login_expired', + 'auth_required', + 'confirmation_required', + 'confirmation_changed', + 'content_removed', + 'insufficient_quota', + 'usage_uncertain', + }.contains(error.code)) + return; + if (!AppLog.instance.errorWasRecorded(error)) { + AppLog.instance.write( + AppLogLevel.error, + 'auto_download', + message, + error: error, + stackTrace: stack, + ); + } + AppLog.instance.requestUploadPrompt(); + } + + /// Cancel pending discovery/admission without removing saved subscriptions. + void invalidatePending() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.invalidatePending", + ); + + _generation++; + _stopReads(); + } + + /// Synchronous invalidation avoids waiting on account locks during restore. + void suspend() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.suspend", + ); + + invalidatePending(); + _suspended = true; + } + + void resume() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.resume", + ); + + if (!_closed) _suspended = false; + } + + void _notify() { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService._notify", + ); + + if (!_changes.isClosed) _changes.add(null); + } + + Future close() async { + AppLog.instance.trace( + "lib/services/auto_download_service.dart::AutoDownloadService.close", + ); + + _closed = true; + suspend(); + await Future.wait(_flights.values.toList()); + await _changes.close(); + } +} + +class _StaleConsent implements Exception { + const _StaleConsent(); +} diff --git a/lib/services/download_service.dart b/lib/services/download_service.dart index 31870ac..1b52049 100644 --- a/lib/services/download_service.dart +++ b/lib/services/download_service.dart @@ -3675,9 +3675,17 @@ class DownloadService { }.contains(cause.code)) { throw const DownloadStopped(); } + // Definitive means the request was rejected, not that retrying is + // futile: rate_limited is definitive too. Stop only known conditions + // which require changed content, credentials, permission or consent. if (attempt >= limit || cause is XmlyException && const { + 'content_removed', + 'login_required', + 'login_expired', + 'permission_denied', + 'insufficient_quota', 'confirmation_changed', 'confirmation_required', 'usage_uncertain', @@ -3833,6 +3841,7 @@ class DownloadService { 'usage_uncertain', 'receipt_required', 'insufficient_quota', + 'content_removed', 'login_required', 'login_expired', 'original_account_required', @@ -3909,6 +3918,8 @@ class DownloadService { return '听时暂时无法确认,正在自动核对,请稍后再试'; case 'insufficient_quota': return '听时不足,请在官方 App 获取听时'; + case 'content_removed': + return '该内容已下架,无法下载'; case 'rate_limited': return '请求过于频繁,已达到重试上限'; case 'login_expired': diff --git a/lib/storage/app_storage.dart b/lib/storage/app_storage.dart index 6442d55..0996433 100644 --- a/lib/storage/app_storage.dart +++ b/lib/storage/app_storage.dart @@ -1,668 +1,655 @@ -import 'dart:convert'; -import 'dart:ffi'; -import 'dart:io'; - -import 'package:ffi/ffi.dart'; -import 'package:path/path.dart' as p; -import 'package:synchronized/synchronized.dart'; -import 'package:uuid/uuid.dart'; -import 'package:win32/win32.dart' as win; - -import '../services/app_log.dart'; - -class StorageException implements Exception { - const StorageException(this.code, this.message); - final String code; - final String message; - @override - String toString() { - AppLog.instance.trace( - "lib/storage/app_storage.dart::StorageException.toString", - ); - return message; - } -} - -/// A single writer owns the OS lock for the complete lifetime of this object. -class AppStorage { - AppStorage._(this.directory, this._lockFile, this._state) { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage._"); - } - - static const maxStateBytes = 64 * 1024 * 1024; - static final Set _openDirectories = {}; - final String directory; - final RandomAccessFile _lockFile; - final Lock _writes = Lock(); - Map _state; - bool _closed = false; - bool _lockClosed = false, _lockUnlocked = false; - - Map get state { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.state.get"); - return _state; - } - - static Future open(String absoluteDirectory) { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.open"); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.open.closure#1", - ); - - if (AppLog.instance.level == AppLogLevel.debug) { - AppLog.instance.write( - AppLogLevel.debug, - 'storage', - 'Opening profile', - data: {'directory': absoluteDirectory}, - ); - } - if (!p.isAbsolute(absoluteDirectory)) { - throw const StorageException('directory', '请选择绝对路径的资料目录'); - } - final Directory folder; - String canonical; - try { - folder = await Directory(absoluteDirectory).create(recursive: true); - canonical = p.normalize(await folder.resolveSymbolicLinks()); - } catch (error, stack) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Opening profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - rethrow; - } - if (Platform.isWindows) canonical = canonical.toLowerCase(); - if (!_openDirectories.add(canonical)) { - throw const StorageException('locked', '数据目录已被另一实例使用'); - } - RandomAccessFile? lock; - try { - lock = await File(p.join(canonical, 'state.lock')) - .open(mode: FileMode.append); - try { - await lock.lock(FileLock.exclusive, 0, 1); - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'storage', - 'Acquiring profile lock failed', - error: error, - stackTrace: stack, - ); - throw const StorageException('locked', '数据目录已被另一实例使用'); - } - final file = File(p.join(canonical, 'state.json')); - Map state; - if (await file.exists()) { - try { - if (await file.length() > maxStateBytes) - throw const FormatException(); - final decoded = jsonDecode(await file.readAsString()); - if (decoded is! Map) throw const FormatException(); - _validate(decoded); - state = decoded; - } catch (error, stack) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Reading profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - const replacement = StorageException( - 'corrupt', - '资料文件损坏,请恢复备份或选择其他资料目录', - ); - AppLog.instance.linkError(replacement, error); - throw replacement; - } - } else { - if (await File(p.join(canonical, 'state.backup')).exists()) { - const error = StorageException( - 'recovery_required', - '资料提交未完成,请保留资料目录并恢复备份', - ); - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Profile recovery required', - error: error, - stackTrace: StackTrace.current, - promptUser: true, - ); - throw error; - } - state = { - 'schemaVersion': 1, - 'activeAccountId': null, - 'primaryAccountId': null, - 'settings': {}, - 'accounts': {}, - 'downloads': [], - 'library': {}, - 'officialProgress': {}, - 'queue': {}, - }; - } - // Only sweep session data while holding the instance lock, before services start. - for (final name in const ['captcha', 'playback-cache']) { - final temporary = Directory(p.join(canonical, name)); - try { - if (await temporary.exists()) - await temporary.delete(recursive: true); - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'storage', - 'Removing old session files failed', - error: error, - stackTrace: stack, - ); - } - } - final storage = AppStorage._(canonical, lock, _freezeMap(state)); - if ((storage.state['settings'] as Map).containsKey( - 'showRequestFailureBanner', - )) { - await storage.transaction((next) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.open.closure#1.closure#1", - ); - - (next['settings'] as Map).remove('showRequestFailureBanner'); - }); - } - return storage; - } catch (error, stack) { - if (!AppLog.instance.errorWasRecorded(error) && - !(error is StorageException && error.code == 'locked')) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Opening profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - } - try { - await lock?.close(); - } catch (cleanupError, cleanupStack) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Closing profile lock failed', - error: cleanupError, - stackTrace: cleanupStack, - promptUser: true, - ); - } - _openDirectories.remove(canonical); - rethrow; - } - }); - } - - Future transaction(void Function(Map) update) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.transaction", - ); - return _writes.synchronized(() { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.transaction.closure#1", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.transaction.closure#1.closure#1", - ); - - if (AppLog.instance.level == AppLogLevel.debug) { - AppLog.instance.write( - AppLogLevel.debug, - 'storage', - 'Profile transaction', - data: {'directory': directory, 'action': update.toString()}, - ); - } - if (_closed) { - const error = StorageException('closed', '资料目录已关闭'); - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Writing closed profile', - error: error, - stackTrace: StackTrace.current, - promptUser: true, - ); - throw error; - } - final next = jsonDecode(jsonEncode(_state)) as Map; - update(next); - final List bytes; - try { - _validate(next); - bytes = utf8.encode(jsonEncode(next)); - } catch (error, stack) { - if (!(error is StorageException && error.code == 'secret_in_state')) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Encoding profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - } else { - AppLog.instance.write( - AppLogLevel.warning, - 'storage', - 'Rejected credentials in profile data', - error: error, - stackTrace: stack, - ); - } - rethrow; - } - if (bytes.length > maxStateBytes) { - throw const StorageException('too_large', '资料超过大小限制,未保存更改'); - } - final temporary = File( - p.join(directory, 'state.${const Uuid().v4()}.tmp'), - ); - try { - final output = await temporary.open(mode: FileMode.writeOnly); - var writeFailed = false; - try { - await output.writeFrom(bytes); - await output.flush(); - } catch (_) { - writeFailed = true; - rethrow; - } finally { - try { - await output.close(); - } catch (error, stack) { - if (!writeFailed) rethrow; - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Closing failed profile write failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - } - } - await _replaceFile(temporary.path, p.join(directory, 'state.json')); - _state = _freezeMap(next); - } on StorageException { - rethrow; - } catch (error, stack) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Writing profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - const replacement = StorageException( - 'write_failed', - '资料保存失败,原有资料未被替换', - ); - AppLog.instance.linkError(replacement, error); - throw replacement; - } finally { - // A failed recovery leaves the backup intact, never delete that file. - try { - if (await temporary.exists()) await temporary.delete(); - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'storage', - 'Removing uncommitted profile file failed', - error: error, - stackTrace: stack, - ); - } - } - }); - }); - } - - Future close() { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.close"); - return _writes.synchronized(() { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.close.closure#1", - ); - return AppLog.instance.runWithErrorScope(() async { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage.close.closure#1.closure#1", - ); - - if (_lockClosed) return; - _closed = true; - var unlockFailed = false; - try { - if (!_lockUnlocked) { - await _lockFile.unlock(0, 1); - _lockUnlocked = true; - } - } catch (error, stack) { - unlockFailed = true; - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Unlocking profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - rethrow; - } finally { - try { - await _lockFile.close(); - _lockClosed = true; - _openDirectories.remove(directory); - } catch (error, stack) { - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Closing profile failed', - error: error, - stackTrace: stack, - promptUser: true, - ); - if (!unlockFailed) rethrow; - } - } - }); - }); - } - - static void _validate(Map value) { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage._validate"); - - if (value['schemaVersion'] != 1 || - value['settings'] is! Map || - value['accounts'] is! Map || - value['downloads'] is! List || - value['library'] is! Map || - (value.containsKey('history') && value['history'] is! Map) || - (value.containsKey('officialProgress') && - value['officialProgress'] is! Map) || - value['queue'] is! Map || - (value['activeAccountId'] != null && - value['activeAccountId'] is! String) || - (value['primaryAccountId'] != null && - value['primaryAccountId'] is! String)) { - throw const StorageException('corrupt', '资料格式无效,未保存更改'); - } - final cleanup = value['credentialCleanup']; - if (cleanup != null && - (cleanup is! List || - cleanup.any((key) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._validate.closure#1", - ); - return key is! String; - }))) { - throw const StorageException('corrupt', '凭据清理记录格式无效'); - } - void inspect(Object? node) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._validate.inspect", - ); - - if (node is Map) { - for (final entry in node.entries) { - if (entry.key is! String || - const { - 'token', - 'device_id', - 'deviceId', - 'cookie', - 'cookie2', - 'x-tk', - 'headers', - 'password', - 'verificationCode', - }.contains(entry.key)) { - throw const StorageException('secret_in_state', '登录秘密不能写入资料文件'); - } - inspect(entry.value); - } - } else if (node is List) { - for (final item in node) { - inspect(item); - } - } else if (node is num && !node.isFinite) { - throw const StorageException('corrupt', '资料包含无效数字'); - } - } - - inspect(value); - // Accept legacy libraries, but never retain their local favorites. - for (final library in (value['library'] as Map).values) { - if (library is Map) library.remove('favorites'); - } - // Keep the cloud-report outbox, not the legacy local history/read model. - final progress = value.putIfAbsent('officialProgress', () { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._validate.closure#2", - ); - return {}; - }) as Map; - final history = value.remove('history') as Map?; - for (final entry in history?.entries ?? const []) { - final pending = entry.value is Map ? entry.value['pending'] : null; - if (pending is! Map) continue; - final current = progress.putIfAbsent(entry.key, () { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._validate.closure#3", - ); - return {}; - }) as Map; - for (final report in pending.entries) { - current.putIfAbsent(report.key, () { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._validate.closure#4", - ); - return report.value; - }); - } - } - } - - static Map _freezeMap(Map value) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._freezeMap", - ); - return Map.unmodifiable( - value.map((key, item) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._freezeMap.closure#1", - ); - return MapEntry(key, _freeze(item)); - }), - ); - } - - static Object? _freeze(Object? value) { - AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage._freeze"); - return value is Map - ? _freezeMap(value) - : value is List - ? List.unmodifiable(value.map(_freeze)) - : value; - } - - static Future _replaceFile(String temporary, String destination) async { - AppLog.instance.trace( - "lib/storage/app_storage.dart::AppStorage._replaceFile", - ); - - if (!Platform.isWindows) { - await File(temporary).rename(destination); - return; - } - _WindowsAtomic.replace(temporary, destination); - } -} - -/// win32 6.4 MoveFileEx returns Win32Result; ReplaceFileW is not exported -/// by that package, so only that missing call has a local FFI declaration. -class _WindowsAtomic { - static final _replace = DynamicLibrary.open('kernel32.dll') - .lookupFunction< - Int32 Function( - Pointer, - Pointer, - Pointer, - Uint32, - Pointer, - Pointer, - ), - int Function( - Pointer, - Pointer, - Pointer, - int, - Pointer, - Pointer, - ) - >('ReplaceFileW'); - - static String _longPath(String value) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::_WindowsAtomic._longPath", - ); - return value.startsWith(r'\\?\') - ? value - : value.startsWith(r'\\') - ? '${r'\\?\UNC\'}${value.substring(2)}' - : '${r'\\?\'}$value'; - } - - static void replace(String temporary, String destination) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::_WindowsAtomic.replace", - ); - - using((arena) { - AppLog.instance.trace( - "lib/storage/app_storage.dart::_WindowsAtomic.replace.closure#1", - ); - - final source = _longPath(temporary).toNativeUtf16(allocator: arena); - final target = _longPath(destination).toNativeUtf16(allocator: arena); - if (!File(destination).existsSync()) { - final moved = win.MoveFileEx( - win.PCWSTR(source), - win.PCWSTR(target), - win.MOVEFILE_WRITE_THROUGH, - ); - if (!moved.value) { - final error = FileSystemException( - 'MoveFileEx failed', - destination, - OSError('Windows error', win.GetLastError().toInt()), - ); - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Replacing profile failed', - error: error, - stackTrace: StackTrace.current, - promptUser: true, - ); - const replacement = StorageException( - 'write_failed', - '资料保存失败,原有资料未被替换', - ); - AppLog.instance.linkError(replacement, error); - throw replacement; - } - return; - } - final backupPath = p.join(p.dirname(destination), 'state.backup'); - // Keep an old backup until replacement succeeds. The API requires the - // backup name to be available; it is never our only live state here. - final backupFile = File(backupPath); - if (backupFile.existsSync()) backupFile.deleteSync(); - final backup = _longPath(backupPath).toNativeUtf16(allocator: arena); - win.GetLastError(); - final result = _replace(target, source, backup, 0, nullptr, nullptr); - final error = win.GetLastError(); - if (result == 0) { - final original = FileSystemException( - 'ReplaceFileW failed', - destination, - OSError('Windows error', error.toInt()), - ); - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Replacing profile failed', - error: original, - stackTrace: StackTrace.current, - promptUser: true, - ); - // 1176/1177 may move the old file. Supplying a backup lets us restore it. - if (!File(destination).existsSync() && backupFile.existsSync()) { - final restored = win.MoveFileEx( - win.PCWSTR(backup), - win.PCWSTR(target), - win.MOVEFILE_WRITE_THROUGH, - ); - if (!restored.value) { - final recoveryError = FileSystemException( - 'MoveFileEx recovery failed', - destination, - OSError('Windows error', win.GetLastError().toInt()), - ); - AppLog.instance.write( - AppLogLevel.error, - 'storage', - 'Recovering profile failed', - error: recoveryError, - stackTrace: StackTrace.current, - promptUser: true, - ); - const replacement = StorageException( - 'recovery_required', - '资料恢复失败,请保留资料目录和备份', - ); - AppLog.instance.linkError(replacement, recoveryError); - throw replacement; - } - } - final replacement = StorageException( - 'write_failed', - '资料保存失败(${error.toInt()}),原有资料未被替换', - ); - AppLog.instance.linkError(replacement, original); - throw replacement; - } - try { - if (backupFile.existsSync()) backupFile.deleteSync(); - } on FileSystemException catch (error, stack) { - AppLog.instance.write( - AppLogLevel.warning, - 'storage', - 'Removing committed profile backup failed', - error: error, - stackTrace: stack, - ); - } - }); - } -} +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; + +import 'package:ffi/ffi.dart'; +import 'package:path/path.dart' as p; +import 'package:synchronized/synchronized.dart'; +import 'package:uuid/uuid.dart'; +import 'package:win32/win32.dart' as win; + +import '../services/app_log.dart'; + +class StorageException implements Exception { + const StorageException(this.code, this.message); + final String code; + final String message; + @override + String toString() { + AppLog.instance.trace( + "lib/storage/app_storage.dart::StorageException.toString", + ); + return message; + } +} + +/// A single writer owns the OS lock for the complete lifetime of this object. +class AppStorage { + AppStorage._(this.directory, this._lockFile, this._state) { + AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage._"); + } + + static const maxStateBytes = 64 * 1024 * 1024; + static final Set _openDirectories = {}; + final String directory; + final RandomAccessFile _lockFile; + final Lock _writes = Lock(); + Map _state; + bool _closed = false; + bool _lockClosed = false, _lockUnlocked = false; + + Map get state { + AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.state.get"); + return _state; + } + + static Future open(String absoluteDirectory) { + AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.open"); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.open.closure#1", + ); + + AppLog.instance.write( + AppLogLevel.info, + 'storage', + 'Opening profile', + data: {'directory': absoluteDirectory}, + ); + if (!p.isAbsolute(absoluteDirectory)) { + throw const StorageException('directory', '请选择绝对路径的资料目录'); + } + final Directory folder; + String canonical; + try { + folder = await Directory(absoluteDirectory).create(recursive: true); + canonical = p.normalize(await folder.resolveSymbolicLinks()); + } catch (error, stack) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Opening profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + rethrow; + } + if (Platform.isWindows) canonical = canonical.toLowerCase(); + if (!_openDirectories.add(canonical)) { + throw const StorageException('locked', '数据目录已被另一实例使用'); + } + RandomAccessFile? lock; + try { + lock = await File(p.join(canonical, 'state.lock')) + .open(mode: FileMode.append); + try { + await lock.lock(FileLock.exclusive, 0, 1); + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'storage', + 'Acquiring profile lock failed', + error: error, + stackTrace: stack, + ); + throw const StorageException('locked', '数据目录已被另一实例使用'); + } + final file = File(p.join(canonical, 'state.json')); + Map state; + if (await file.exists()) { + try { + if (await file.length() > maxStateBytes) + throw const FormatException(); + final decoded = jsonDecode(await file.readAsString()); + if (decoded is! Map) throw const FormatException(); + _validate(decoded); + state = decoded; + } catch (error, stack) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Reading profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + const replacement = StorageException( + 'corrupt', + '资料文件损坏,请恢复备份或选择其他资料目录', + ); + AppLog.instance.linkError(replacement, error); + throw replacement; + } + } else { + if (await File(p.join(canonical, 'state.backup')).exists()) { + const error = StorageException( + 'recovery_required', + '资料提交未完成,请保留资料目录并恢复备份', + ); + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Profile recovery required', + error: error, + stackTrace: StackTrace.current, + promptUser: true, + ); + throw error; + } + state = { + 'schemaVersion': 1, + 'activeAccountId': null, + 'primaryAccountId': null, + 'settings': {}, + 'accounts': {}, + 'downloads': [], + 'library': {}, + 'officialProgress': {}, + 'queue': {}, + }; + } + // Only sweep session data while holding the instance lock, before services start. + for (final name in const ['captcha', 'playback-cache']) { + final temporary = Directory(p.join(canonical, name)); + try { + if (await temporary.exists()) + await temporary.delete(recursive: true); + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'storage', + 'Removing old session files failed', + error: error, + stackTrace: stack, + ); + } + } + final storage = AppStorage._(canonical, lock, _freezeMap(state)); + if ((storage.state['settings'] as Map).containsKey( + 'showRequestFailureBanner', + )) { + await storage.transaction((next) { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.open.closure#1.closure#1", + ); + + (next['settings'] as Map).remove('showRequestFailureBanner'); + }); + } + AppLog.instance.write(AppLogLevel.info, 'storage', 'Profile opened'); + return storage; + } catch (error, stack) { + if (!AppLog.instance.errorWasRecorded(error) && + !(error is StorageException && error.code == 'locked')) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Opening profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + } + try { + await lock?.close(); + } catch (cleanupError, cleanupStack) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Closing profile lock failed', + error: cleanupError, + stackTrace: cleanupStack, + promptUser: true, + ); + } + _openDirectories.remove(canonical); + rethrow; + } + }); + } + + Future transaction(void Function(Map) update) { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.transaction", + ); + return _writes.synchronized(() { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.transaction.closure#1", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.transaction.closure#1.closure#1", + ); + + if (AppLog.instance.level == AppLogLevel.debug) { + AppLog.instance.write( + AppLogLevel.debug, + 'storage', + 'Profile transaction', + data: {'directory': directory, 'action': update.toString()}, + ); + } + if (_closed) { + const error = StorageException('closed', '资料目录已关闭'); + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Writing closed profile', + error: error, + stackTrace: StackTrace.current, + promptUser: true, + ); + throw error; + } + final next = jsonDecode(jsonEncode(_state)) as Map; + update(next); + final List bytes; + try { + _validate(next); + bytes = utf8.encode(jsonEncode(next)); + } catch (error, stack) { + if (!(error is StorageException && error.code == 'secret_in_state')) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Encoding profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + } else { + AppLog.instance.write( + AppLogLevel.warning, + 'storage', + 'Rejected credentials in profile data', + error: error, + stackTrace: stack, + ); + } + rethrow; + } + if (bytes.length > maxStateBytes) { + throw const StorageException('too_large', '资料超过大小限制,未保存更改'); + } + final temporary = File( + p.join(directory, 'state.${const Uuid().v4()}.tmp'), + ); + try { + final output = await temporary.open(mode: FileMode.writeOnly); + var writeFailed = false; + try { + await output.writeFrom(bytes); + await output.flush(); + } catch (_) { + writeFailed = true; + rethrow; + } finally { + try { + await output.close(); + } catch (error, stack) { + if (!writeFailed) rethrow; + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Closing failed profile write failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + } + } + await _replaceFile(temporary.path, p.join(directory, 'state.json')); + _state = _freezeMap(next); + } on StorageException { + rethrow; + } catch (error, stack) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Writing profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + const replacement = StorageException( + 'write_failed', + '资料保存失败,原有资料未被替换', + ); + AppLog.instance.linkError(replacement, error); + throw replacement; + } finally { + // A failed recovery leaves the backup intact, never delete that file. + try { + if (await temporary.exists()) await temporary.delete(); + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'storage', + 'Removing uncommitted profile file failed', + error: error, + stackTrace: stack, + ); + } + } + }); + }); + } + + Future close() { + AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage.close"); + return _writes.synchronized(() { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.close.closure#1", + ); + return AppLog.instance.runWithErrorScope(() async { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage.close.closure#1.closure#1", + ); + + if (_lockClosed) return; + _closed = true; + var unlockFailed = false; + try { + if (!_lockUnlocked) { + await _lockFile.unlock(0, 1); + _lockUnlocked = true; + } + } catch (error, stack) { + unlockFailed = true; + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Unlocking profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + rethrow; + } finally { + try { + await _lockFile.close(); + _lockClosed = true; + _openDirectories.remove(directory); + } catch (error, stack) { + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Closing profile failed', + error: error, + stackTrace: stack, + promptUser: true, + ); + if (!unlockFailed) rethrow; + } + } + }); + }); + } + + static void _validate(Map value) { + AppLog.instance.trace("lib/storage/app_storage.dart::AppStorage._validate"); + + if (value['schemaVersion'] != 1 || + value['settings'] is! Map || + value['accounts'] is! Map || + value['downloads'] is! List || + value['library'] is! Map || + (value.containsKey('history') && value['history'] is! Map) || + (value.containsKey('officialProgress') && + value['officialProgress'] is! Map) || + value['queue'] is! Map || + (value['activeAccountId'] != null && + value['activeAccountId'] is! String) || + (value['primaryAccountId'] != null && + value['primaryAccountId'] is! String)) { + throw const StorageException('corrupt', '资料格式无效,未保存更改'); + } + final cleanup = value['credentialCleanup']; + if (cleanup != null && + (cleanup is! List || + cleanup.any((key) { + // Trace-exempt hot path: one invocation per cleanup entry. + return key is! String; + }))) { + throw const StorageException('corrupt', '凭据清理记录格式无效'); + } + void inspect(Object? node) { + // Trace-exempt hot path: validation visits every persisted value. + + if (node is Map) { + for (final entry in node.entries) { + if (entry.key is! String || + const { + 'token', + 'device_id', + 'deviceId', + 'cookie', + 'cookie2', + 'x-tk', + 'headers', + 'password', + 'verificationCode', + }.contains(entry.key)) { + throw const StorageException('secret_in_state', '登录秘密不能写入资料文件'); + } + inspect(entry.value); + } + } else if (node is List) { + for (final item in node) { + inspect(item); + } + } else if (node is num && !node.isFinite) { + throw const StorageException('corrupt', '资料包含无效数字'); + } + } + + inspect(value); + // Accept legacy libraries, but never retain their local favorites. + for (final library in (value['library'] as Map).values) { + if (library is Map) library.remove('favorites'); + } + // Keep the cloud-report outbox, not the legacy local history/read model. + final progress = value.putIfAbsent('officialProgress', () { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage._validate.closure#2", + ); + return {}; + }) as Map; + final history = value.remove('history') as Map?; + for (final entry in history?.entries ?? const []) { + final pending = entry.value is Map ? entry.value['pending'] : null; + if (pending is! Map) continue; + final current = progress.putIfAbsent(entry.key, () { + // Trace-exempt hot path: one invocation per legacy progress entry. + return {}; + }) as Map; + for (final report in pending.entries) { + current.putIfAbsent(report.key, () { + // Trace-exempt hot path: one invocation per pending report. + return report.value; + }); + } + } + } + + static Map _freezeMap(Map value) { + // Trace-exempt hot path: recursive freezing is covered by operation traces. + return Map.unmodifiable( + value.map((key, item) { + // Trace-exempt hot path: one invocation per map field. + return MapEntry(key, _freeze(item)); + }), + ); + } + + static Object? _freeze(Object? value) { + // Trace-exempt hot path: one invocation per persisted value. + return value is Map + ? _freezeMap(value) + : value is List + ? List.unmodifiable(value.map(_freeze)) + : value; + } + + static Future _replaceFile(String temporary, String destination) async { + AppLog.instance.trace( + "lib/storage/app_storage.dart::AppStorage._replaceFile", + ); + + if (!Platform.isWindows) { + await File(temporary).rename(destination); + return; + } + _WindowsAtomic.replace(temporary, destination); + } +} + +/// win32 6.4 MoveFileEx returns Win32Result; ReplaceFileW is not exported +/// by that package, so only that missing call has a local FFI declaration. +class _WindowsAtomic { + static final _replace = DynamicLibrary.open('kernel32.dll') + .lookupFunction< + Int32 Function( + Pointer, + Pointer, + Pointer, + Uint32, + Pointer, + Pointer, + ), + int Function( + Pointer, + Pointer, + Pointer, + int, + Pointer, + Pointer, + ) + >('ReplaceFileW'); + + static String _longPath(String value) { + AppLog.instance.trace( + "lib/storage/app_storage.dart::_WindowsAtomic._longPath", + ); + return value.startsWith(r'\\?\') + ? value + : value.startsWith(r'\\') + ? '${r'\\?\UNC\'}${value.substring(2)}' + : '${r'\\?\'}$value'; + } + + static void replace(String temporary, String destination) { + AppLog.instance.trace( + "lib/storage/app_storage.dart::_WindowsAtomic.replace", + ); + + using((arena) { + AppLog.instance.trace( + "lib/storage/app_storage.dart::_WindowsAtomic.replace.closure#1", + ); + + final source = _longPath(temporary).toNativeUtf16(allocator: arena); + final target = _longPath(destination).toNativeUtf16(allocator: arena); + if (!File(destination).existsSync()) { + final moved = win.MoveFileEx( + win.PCWSTR(source), + win.PCWSTR(target), + win.MOVEFILE_WRITE_THROUGH, + ); + if (!moved.value) { + final error = FileSystemException( + 'MoveFileEx failed', + destination, + OSError('Windows error', win.GetLastError().toInt()), + ); + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Replacing profile failed', + error: error, + stackTrace: StackTrace.current, + promptUser: true, + ); + const replacement = StorageException( + 'write_failed', + '资料保存失败,原有资料未被替换', + ); + AppLog.instance.linkError(replacement, error); + throw replacement; + } + return; + } + final backupPath = p.join(p.dirname(destination), 'state.backup'); + // Keep an old backup until replacement succeeds. The API requires the + // backup name to be available; it is never our only live state here. + final backupFile = File(backupPath); + if (backupFile.existsSync()) backupFile.deleteSync(); + final backup = _longPath(backupPath).toNativeUtf16(allocator: arena); + win.GetLastError(); + final result = _replace(target, source, backup, 0, nullptr, nullptr); + final error = win.GetLastError(); + if (result == 0) { + final original = FileSystemException( + 'ReplaceFileW failed', + destination, + OSError('Windows error', error.toInt()), + ); + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Replacing profile failed', + error: original, + stackTrace: StackTrace.current, + promptUser: true, + ); + // 1176/1177 may move the old file. Supplying a backup lets us restore it. + if (!File(destination).existsSync() && backupFile.existsSync()) { + final restored = win.MoveFileEx( + win.PCWSTR(backup), + win.PCWSTR(target), + win.MOVEFILE_WRITE_THROUGH, + ); + if (!restored.value) { + final recoveryError = FileSystemException( + 'MoveFileEx recovery failed', + destination, + OSError('Windows error', win.GetLastError().toInt()), + ); + AppLog.instance.write( + AppLogLevel.error, + 'storage', + 'Recovering profile failed', + error: recoveryError, + stackTrace: StackTrace.current, + promptUser: true, + ); + const replacement = StorageException( + 'recovery_required', + '资料恢复失败,请保留资料目录和备份', + ); + AppLog.instance.linkError(replacement, recoveryError); + throw replacement; + } + } + final replacement = StorageException( + 'write_failed', + '资料保存失败(${error.toInt()}),原有资料未被替换', + ); + AppLog.instance.linkError(replacement, original); + throw replacement; + } + try { + if (backupFile.existsSync()) backupFile.deleteSync(); + } on FileSystemException catch (error, stack) { + AppLog.instance.write( + AppLogLevel.warning, + 'storage', + 'Removing committed profile backup failed', + error: error, + stackTrace: stack, + ); + } + }); + } +} diff --git a/packages/xmplus_android_background/android/build.gradle.kts b/packages/xmplus_android_background/android/build.gradle.kts new file mode 100644 index 0000000..5bfcc7a --- /dev/null +++ b/packages/xmplus_android_background/android/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + id("com.android.library") +} + +android { + namespace = "teikengstudio.xmplus.background" + compileSdk = 36 + defaultConfig { + minSdk = 26 + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} diff --git a/packages/xmplus_android_background/android/src/main/AndroidManifest.xml b/packages/xmplus_android_background/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..9b8215b --- /dev/null +++ b/packages/xmplus_android_background/android/src/main/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadBackgroundPlugin.kt b/packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadBackgroundPlugin.kt new file mode 100644 index 0000000..a9c2452 --- /dev/null +++ b/packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadBackgroundPlugin.kt @@ -0,0 +1,158 @@ +package teikengstudio.xmplus.background + +import android.Manifest +import android.app.NotificationManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.os.PowerManager +import android.os.ResultReceiver +import android.provider.Settings +import android.widget.Toast +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.PluginRegistry + +/** Engine-owned commands remain available while audio_service has no Activity. */ +class DownloadBackgroundPlugin : FlutterPlugin, ActivityAware, + MethodChannel.MethodCallHandler, PluginRegistry.RequestPermissionsResultListener { + private lateinit var context: Context + private lateinit var messenger: BinaryMessenger + private lateinit var channel: MethodChannel + private var activityBinding: ActivityPluginBinding? = null + private var notificationPermissionResult: MethodChannel.Result? = null + private val notificationPermissionRequest = 2102 + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + context = binding.applicationContext + messenger = binding.binaryMessenger + channel = MethodChannel(messenger, DownloadForegroundService.CHANNEL) + channel.setMethodCallHandler(this) + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + channel.setMethodCallHandler(null) + detachActivity() + if (DownloadForegroundService.messenger === messenger) { + DownloadForegroundService.messenger = null + // The engine owns the workers: no engine means no work to advertise. + context.stopService(Intent(context, DownloadForegroundService::class.java)) + } + } + + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + activityBinding = binding + binding.addRequestPermissionsResultListener(this) + } + + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) = onAttachedToActivity(binding) + override fun onDetachedFromActivityForConfigChanges() = detachActivity() + override fun onDetachedFromActivity() = detachActivity() + + private fun detachActivity() { + activityBinding?.removeRequestPermissionsResultListener(this) + activityBinding = null + notificationPermissionResult?.success(false) + notificationPermissionResult = null + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray): Boolean { + if (requestCode != notificationPermissionRequest) return false + notificationPermissionResult?.success( + grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED + ) + notificationPermissionResult = null + return true + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + try { + when (call.method) { + "downloadNotificationPermission" -> { + val enabled = context.getSystemService(NotificationManager::class.java).areNotificationsEnabled() + val activity = activityBinding?.activity + if (enabled || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + call.argument("request") != true || activity == null) { + result.success(enabled) + } else if (notificationPermissionResult != null) { + result.error("permission_pending", "通知权限请求尚未结束", null) + } else { + notificationPermissionResult = result + try { + activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), notificationPermissionRequest) + } catch (error: Exception) { + notificationPermissionResult = null + throw error + } + } + } + "downloadForeground" -> { + val intent = Intent(context, DownloadForegroundService::class.java).apply { + putExtra("title", requireNotNull(call.argument("title"))) + putExtra("text", requireNotNull(call.argument("text"))) + putExtra("receivedBytes", requireNotNull(call.argument("receivedBytes")).toLong()) + putExtra("totalBytes", call.argument("totalBytes")?.toLong() ?: 0L) + } + DownloadForegroundService.messenger = messenger + val service = DownloadForegroundService.instance + if (service != null) { + service.update(intent) + result.success(null) + } else { + intent.putExtra("reply", object : ResultReceiver(Handler(Looper.getMainLooper())) { + override fun onReceiveResult(code: Int, data: Bundle?) { + if (code == 0) result.success(null) + else result.error("download_foreground", data?.getString("error"), null) + } + }) + context.startForegroundService(intent) + } + } + "stopDownloadForeground" -> { + val owner = DownloadForegroundService.messenger + if (owner != null && owner !== messenger) { + result.success(null) + return + } + val service = DownloadForegroundService.instance + if (service != null) { + service.stopPresenting { result.success(null) } + } else { + context.stopService(Intent(context, DownloadForegroundService::class.java)) + result.success(null) + } + // Clear now, not in onDestroy: another engine may start before that callback. + DownloadForegroundService.messenger = null + } + "batteryOptimizationExempt" -> result.success( + context.getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(context.packageName) + ) + "requestBatteryOptimizationExemption" -> { + val activity = checkNotNull(activityBinding?.activity) { "Activity is not attached" } + activity.startActivity(Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, + Uri.parse("package:${context.packageName}"))) + result.success(null) + } + "showDownloadBackgroundError" -> { + Toast.makeText(context, call.argument("message"), Toast.LENGTH_LONG).show() + result.success(null) + } + else -> result.notImplemented() + } + } catch (error: Exception) { + if (call.method == "downloadForeground") { + Toast.makeText(context, "下载后台服务启动失败,请保持应用在前台:${error.message}", Toast.LENGTH_LONG).show() + } + result.error("android_background", error.message, null) + } + } +} diff --git a/android/app/src/main/kotlin/teikengstudio/xmplus/DownloadForegroundService.kt b/packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadForegroundService.kt similarity index 96% rename from android/app/src/main/kotlin/teikengstudio/xmplus/DownloadForegroundService.kt rename to packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadForegroundService.kt index 8c3b469..2b7e9b8 100644 --- a/android/app/src/main/kotlin/teikengstudio/xmplus/DownloadForegroundService.kt +++ b/packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadForegroundService.kt @@ -1,4 +1,4 @@ -package teikengstudio.xmplus +package teikengstudio.xmplus.background import android.app.Notification import android.app.NotificationChannel @@ -95,7 +95,8 @@ class DownloadForegroundService : Service() { private fun notification(intent: Intent): Notification { val openApp = PendingIntent.getActivity( this, 0, - Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP), + requireNotNull(packageManager.getLaunchIntentForPackage(packageName)) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) val total = intent.getLongExtra("totalBytes", 0) diff --git a/android/app/src/main/res/drawable/ic_download_notification.xml b/packages/xmplus_android_background/android/src/main/res/drawable/ic_download_notification.xml similarity index 100% rename from android/app/src/main/res/drawable/ic_download_notification.xml rename to packages/xmplus_android_background/android/src/main/res/drawable/ic_download_notification.xml diff --git a/packages/xmplus_android_background/pubspec.yaml b/packages/xmplus_android_background/pubspec.yaml new file mode 100644 index 0000000..8295311 --- /dev/null +++ b/packages/xmplus_android_background/pubspec.yaml @@ -0,0 +1,16 @@ +name: xmplus_android_background +description: Android download foreground channel for every XMPlus Flutter engine. +version: 1.0.0 +publish_to: none +environment: + sdk: '>=3.13.7 <4.0.0' + flutter: '>=3.47.9' +dependencies: + flutter: + sdk: flutter +flutter: + plugin: + platforms: + android: + package: teikengstudio.xmplus.background + pluginClass: DownloadBackgroundPlugin diff --git a/pubspec.lock b/pubspec.lock index f3975eb..daa5e21 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1,1178 +1,1185 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - _fe_analyzer_shared: - dependency: transitive - description: - name: _fe_analyzer_shared - sha256: "1c5591cc6f252d5f440d96ab87c03e43504be552a3fa49d7cb7563f04c51fb0a" - url: "https://pub.dev" - source: hosted - version: "111.0.0" - analyzer: - dependency: "direct dev" - description: - name: analyzer - sha256: "6c39bd5486a310e56217bed7cb1691377959f31be4227e41750107db7e6dd55c" - url: "https://pub.dev" - source: hosted - version: "14.7.0" - android_file_picker: - dependency: transitive - description: - name: android_file_picker - sha256: "868183c959e754e915954d8074c20cfa4cfdb4684b35ecc08378437be1a542d8" - url: "https://pub.dev" - source: hosted - version: "2.1.3" - ansicolor: - dependency: transitive - description: - name: ansicolor - sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f" - url: "https://pub.dev" - source: hosted - version: "2.0.3" - archive: - dependency: "direct main" - description: - name: archive - sha256: de5ac590b8155e4e676088d714bd41ea620449a6adc0f7950c5073874b287ddb - url: "https://pub.dev" - source: hosted - version: "4.6.0" - args: - dependency: transitive - description: - name: args - sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 - url: "https://pub.dev" - source: hosted - version: "2.7.0" - asn1lib: - dependency: transitive - description: - name: asn1lib - sha256: cfb3cf6a53158918d52dda61bc26f0cc8612a0d3b9dc29e87eaa3423902ca636 - url: "https://pub.dev" - source: hosted - version: "1.6.8" - async: - dependency: transitive - description: - name: async - sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 - url: "https://pub.dev" - source: hosted - version: "2.13.1" - audio_service: - dependency: "direct main" - description: - name: audio_service - sha256: "95f3267f3449eb5cf71c8fcf1d556f57af1e898e2dc5815fb168d1843653edb7" - url: "https://pub.dev" - source: hosted - version: "0.18.19" - audio_service_platform_interface: - dependency: "direct main" - description: - name: audio_service_platform_interface - sha256: "6283782851f6c8b501b60904a32fc7199dc631172da0629d7301e66f672ab777" - url: "https://pub.dev" - source: hosted - version: "0.1.3" - audio_service_web: - dependency: transitive - description: - name: audio_service_web - sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df - url: "https://pub.dev" - source: hosted - version: "0.1.4" - audio_session: - dependency: "direct main" - description: - name: audio_session - sha256: f9e7711a0e24ca8b40f5d7ac374c3c6e55016f3157912badd18199cdbbca5c4d - url: "https://pub.dev" - source: hosted - version: "0.2.4" - characters: - dependency: transitive - description: - name: characters - sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b - url: "https://pub.dev" - source: hosted - version: "1.4.1" - clock: - dependency: transitive - description: - name: clock - sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e - url: "https://pub.dev" - source: hosted - version: "1.1.3" - cnativeapi: - dependency: transitive - description: - name: cnativeapi - sha256: c43703998995e132b0656d2b8a95ed2bedc6b22ccee2c827bcdc075e0330e319 - url: "https://pub.dev" - source: hosted - version: "0.5.10" - code_assets: - dependency: transitive - description: - name: code_assets - sha256: "1ef22a0be3af9370bd9481ac76db114db92bfe75d5ca2b2d7bc911764478a4d9" - url: "https://pub.dev" - source: hosted - version: "2.2.0" - collection: - dependency: transitive - description: - name: collection - sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" - url: "https://pub.dev" - source: hosted - version: "1.19.1" - convert: - dependency: transitive - description: - name: convert - sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 - url: "https://pub.dev" - source: hosted - version: "3.1.2" - cross_file: - dependency: transitive - description: - name: cross_file - sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 - url: "https://pub.dev" - source: hosted - version: "0.3.5+5" - crypto: - dependency: "direct main" - description: - name: crypto - sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 - url: "https://pub.dev" - source: hosted - version: "3.0.8" - cupertino_ui: - dependency: transitive - description: - name: cupertino_ui - sha256: "369e39a1c5c030a6212589c3da1809920b1c2cfade7b02aade7695bfa4b88c3a" - url: "https://pub.dev" - source: hosted - version: "1.1.6" - dbus: - dependency: transitive - description: - name: dbus - sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 - url: "https://pub.dev" - source: hosted - version: "0.8.0" - device_info_plus: - dependency: "direct main" - description: - name: device_info_plus - sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa - url: "https://pub.dev" - source: hosted - version: "13.3.0" - device_info_plus_platform_interface: - dependency: transitive - description: - name: device_info_plus_platform_interface - sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" - url: "https://pub.dev" - source: hosted - version: "8.1.0" - dio: - dependency: "direct main" - description: - name: dio - sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1" - url: "https://pub.dev" - source: hosted - version: "5.11.1" - dio_web_adapter: - dependency: transitive - description: - name: dio_web_adapter - sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc" - url: "https://pub.dev" - source: hosted - version: "2.2.2" - encrypt: - dependency: "direct main" - description: - name: encrypt - sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2" - url: "https://pub.dev" - source: hosted - version: "5.0.3" - ffi: - dependency: "direct main" - description: - name: ffi - sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" - url: "https://pub.dev" - source: hosted - version: "2.2.0" - ffi_leak_tracker: - dependency: transitive - description: - name: ffi_leak_tracker - sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" - url: "https://pub.dev" - source: hosted - version: "0.1.2" - file: - dependency: transitive - description: - name: file - sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 - url: "https://pub.dev" - source: hosted - version: "7.0.1" - file_picker: - dependency: "direct main" - description: - name: file_picker - sha256: c64036857780d7125f011d543f89eedcb5df61da473668bace4eee9ab875284d - url: "https://pub.dev" - source: hosted - version: "13.3.2" - file_picker_darwin: - dependency: transitive - description: - name: file_picker_darwin - sha256: daeb0219f6279c73eb9c63ae9a566beef04ae13d59b8feba0be2a7f3b258d3d4 - url: "https://pub.dev" - source: hosted - version: "2.4.2" - file_picker_linux: - dependency: transitive - description: - name: file_picker_linux - sha256: eb00de71b123e91d3c61f389a05b8cc90f9cbe7e4c88da30ebe2f0442b281b61 - url: "https://pub.dev" - source: hosted - version: "2.0.3" - file_picker_platform_interface: - dependency: transitive - description: - name: file_picker_platform_interface - sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" - url: "https://pub.dev" - source: hosted - version: "4.2.0" - file_picker_web: - dependency: transitive - description: - name: file_picker_web - sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c - url: "https://pub.dev" - source: hosted - version: "4.2.0" - fixnum: - dependency: transitive - description: - name: fixnum - sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be - url: "https://pub.dev" - source: hosted - version: "1.1.1" - flutter: - dependency: "direct main" - description: flutter - source: sdk - version: "0.0.0" - flutter_cache_manager: - dependency: transitive - description: - name: flutter_cache_manager - sha256: a42024cf8bbb7e1f4d2875301660f62543601a4c3b20119ea9a683e4d191d0f4 - url: "https://pub.dev" - source: hosted - version: "3.5.0" - flutter_inappwebview: - dependency: "direct main" - description: - name: flutter_inappwebview - sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5" - url: "https://pub.dev" - source: hosted - version: "6.1.5" - flutter_inappwebview_android: - dependency: transitive - description: - name: flutter_inappwebview_android - sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" - url: "https://pub.dev" - source: hosted - version: "1.1.3" - flutter_inappwebview_internal_annotations: - dependency: transitive - description: - name: flutter_inappwebview_internal_annotations - sha256: e30fba942e3debea7b7e6cdd4f0f59ce89dd403a9865193e3221293b6d1544c6 - url: "https://pub.dev" - source: hosted - version: "1.3.0" - flutter_inappwebview_ios: - dependency: transitive - description: - name: flutter_inappwebview_ios - sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" - url: "https://pub.dev" - source: hosted - version: "1.1.2" - flutter_inappwebview_macos: - dependency: transitive - description: - name: flutter_inappwebview_macos - sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 - url: "https://pub.dev" - source: hosted - version: "1.1.2" - flutter_inappwebview_platform_interface: - dependency: transitive - description: - name: flutter_inappwebview_platform_interface - sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 - url: "https://pub.dev" - source: hosted - version: "1.3.0+1" - flutter_inappwebview_web: - dependency: transitive - description: - name: flutter_inappwebview_web - sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" - url: "https://pub.dev" - source: hosted - version: "1.1.2" - flutter_inappwebview_windows: - dependency: transitive - description: - name: flutter_inappwebview_windows - sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055" - url: "https://pub.dev" - source: hosted - version: "0.6.0" - flutter_localizations: - dependency: "direct main" - description: flutter - source: sdk - version: "0.0.0" - flutter_secure_storage: - dependency: "direct main" - description: - name: flutter_secure_storage - sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 - url: "https://pub.dev" - source: hosted - version: "11.2.0" - flutter_secure_storage_darwin: - dependency: transitive - description: - name: flutter_secure_storage_darwin - sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 - url: "https://pub.dev" - source: hosted - version: "0.4.3" - flutter_secure_storage_linux: - dependency: transitive - description: - name: flutter_secure_storage_linux - sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea - url: "https://pub.dev" - source: hosted - version: "3.0.3" - flutter_secure_storage_platform_interface: - dependency: transitive - description: - name: flutter_secure_storage_platform_interface - sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" - url: "https://pub.dev" - source: hosted - version: "2.1.1" - flutter_secure_storage_web: - dependency: transitive - description: - name: flutter_secure_storage_web - sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" - url: "https://pub.dev" - source: hosted - version: "2.1.1" - flutter_secure_storage_windows: - dependency: transitive - description: - name: flutter_secure_storage_windows - sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" - url: "https://pub.dev" - source: hosted - version: "4.2.2" - flutter_web_plugins: - dependency: transitive - description: flutter - source: sdk - version: "0.0.0" - get: - dependency: "direct main" - description: - name: get - sha256: "5ed34a7925b85336e15d472cc4cfe7d9ebf4ab8e8b9f688585bf6b50f4c3d79a" - url: "https://pub.dev" - source: hosted - version: "4.7.3" - glob: - dependency: transitive - description: - name: glob - sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" - url: "https://pub.dev" - source: hosted - version: "2.2.0" - globbing: - dependency: transitive - description: - name: globbing - sha256: "4f89cfaf6fa74c9c1740a96259da06bd45411ede56744e28017cc534a12b6e2d" - url: "https://pub.dev" - source: hosted - version: "1.0.0" - hooks: - dependency: transitive - description: - name: hooks - sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f - url: "https://pub.dev" - source: hosted - version: "2.2.0" - http: - dependency: transitive - description: - name: http - sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" - url: "https://pub.dev" - source: hosted - version: "1.6.0" - http_parser: - dependency: transitive - description: - name: http_parser - sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" - url: "https://pub.dev" - source: hosted - version: "4.1.2" - image: - dependency: transitive - description: - name: image - sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" - url: "https://pub.dev" - source: hosted - version: "4.12.0" - injector: - dependency: transitive - description: - name: injector - sha256: ed389bed5b48a699d5b9561c985023d0d5cc88dd5ff2237aadcce5a5ab433e4e - url: "https://pub.dev" - source: hosted - version: "3.0.0" - intl: - dependency: transitive - description: - name: intl - sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" - url: "https://pub.dev" - source: hosted - version: "0.20.3" - jni: - dependency: transitive - description: - name: jni - sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c" - url: "https://pub.dev" - source: hosted - version: "1.1.2" - jni_flutter: - dependency: transitive - description: - name: jni_flutter - sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" - url: "https://pub.dev" - source: hosted - version: "1.0.4+1" - jni_util: - dependency: transitive - description: - name: jni_util - sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" - url: "https://pub.dev" - source: hosted - version: "1.0.0" - js: - dependency: transitive - description: - name: js - sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" - url: "https://pub.dev" - source: hosted - version: "0.7.2" - json_annotation: - dependency: transitive - description: - name: json_annotation - sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" - url: "https://pub.dev" - source: hosted - version: "4.12.0" - logging: - dependency: transitive - description: - name: logging - sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 - url: "https://pub.dev" - source: hosted - version: "1.3.0" - material_color_utilities: - dependency: transitive - description: - name: material_color_utilities - sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" - url: "https://pub.dev" - source: hosted - version: "0.13.0" - material_ui: - dependency: "direct main" - description: - name: material_ui - sha256: d9b4f6c69b80bc83d0a14357c86e4c14c8076e807ae73cf2960c8560f623995f - url: "https://pub.dev" - source: hosted - version: "1.0.0" - media_kit: - dependency: "direct main" - description: - name: media_kit - sha256: ae9e79597500c7ad6083a3c7b7b7544ddabfceacce7ae5c9709b0ec16a5d6643 - url: "https://pub.dev" - source: hosted - version: "1.2.6" - media_kit_libs_android_audio: - dependency: transitive - description: - name: media_kit_libs_android_audio - sha256: "8f8f9759e537e12d66f08bc4d5279eb1bb21a0ccc519ff3442c68a9f3b6dd68b" - url: "https://pub.dev" - source: hosted - version: "1.3.8" - media_kit_libs_audio: - dependency: "direct main" - description: - name: media_kit_libs_audio - sha256: "81bf506c234e81e3ec536ba72f8f700a928543c14c345220210cae0411636316" - url: "https://pub.dev" - source: hosted - version: "1.0.7" - media_kit_libs_ios_audio: - dependency: transitive - description: - name: media_kit_libs_ios_audio - sha256: "78ccf04e27d6b4ba00a355578ccb39b772f00d48269a6ac3db076edf2d51934f" - url: "https://pub.dev" - source: hosted - version: "1.1.4" - media_kit_libs_linux: - dependency: transitive - description: - name: media_kit_libs_linux - sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf" - url: "https://pub.dev" - source: hosted - version: "1.2.1" - media_kit_libs_macos_audio: - dependency: transitive - description: - name: media_kit_libs_macos_audio - sha256: "3be21844df98f286de32808592835073cdef2c1a10078bac135da790badca950" - url: "https://pub.dev" - source: hosted - version: "1.1.4" - media_kit_libs_windows_audio: - dependency: transitive - description: - name: media_kit_libs_windows_audio - sha256: c2fd558cc87b9d89a801141fcdffe02e338a3b21a41a18fbd63d5b221a1b8e53 - url: "https://pub.dev" - source: hosted - version: "1.0.9" - meta: - dependency: transitive - description: - name: meta - sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" - url: "https://pub.dev" - source: hosted - version: "1.19.0" - mime: - dependency: transitive - description: - name: mime - sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 - url: "https://pub.dev" - source: hosted - version: "2.1.0" - native_toolchain_c: - dependency: transitive - description: - name: native_toolchain_c - sha256: "120b6fc66acd8a5ddeaeb1e59b78836bb3ec9919bd9d9dfb1e2401985710c2c0" - url: "https://pub.dev" - source: hosted - version: "0.19.6" - nativeapi: - dependency: transitive - description: - name: nativeapi - sha256: "118045bb549cb6fabad472a3a22a537e7310bbf20097350f5027808b4a5853ce" - url: "https://pub.dev" - source: hosted - version: "0.5.10" - nativeapi_flutter: - dependency: transitive - description: - name: nativeapi_flutter - sha256: "357a405c69212f5157da1bd3be183a53c2b841d0de0eb51f4a3947913712aec4" - url: "https://pub.dev" - source: hosted - version: "0.5.10" - objective_c: - dependency: transitive - description: - name: objective_c - sha256: "322d5f1f0680534acaf557c5d68e97b40c3800ee5e15b63dcacc3c31504674c2" - url: "https://pub.dev" - source: hosted - version: "9.6.3" - package_config: - dependency: transitive - description: - name: package_config - sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d - url: "https://pub.dev" - source: hosted - version: "3.0.0" - package_info_plus: - dependency: "direct main" - description: - name: package_info_plus - sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" - url: "https://pub.dev" - source: hosted - version: "10.2.2" - package_info_plus_platform_interface: - dependency: transitive - description: - name: package_info_plus_platform_interface - sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 - url: "https://pub.dev" - source: hosted - version: "4.1.0" - path: - dependency: "direct main" - description: - name: path - sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" - url: "https://pub.dev" - source: hosted - version: "1.9.1" - path_provider: - dependency: "direct main" - description: - name: path_provider - sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 - url: "https://pub.dev" - source: hosted - version: "2.1.6" - path_provider_android: - dependency: transitive - description: - name: path_provider_android - sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" - url: "https://pub.dev" - source: hosted - version: "2.3.1" - path_provider_foundation: - dependency: transitive - description: - name: path_provider_foundation - sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" - url: "https://pub.dev" - source: hosted - version: "2.6.0" - path_provider_linux: - dependency: transitive - description: - name: path_provider_linux - sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" - url: "https://pub.dev" - source: hosted - version: "2.2.2" - path_provider_platform_interface: - dependency: transitive - description: - name: path_provider_platform_interface - sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" - url: "https://pub.dev" - source: hosted - version: "2.1.3" - path_provider_windows: - dependency: transitive - description: - name: path_provider_windows - sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 - url: "https://pub.dev" - source: hosted - version: "2.3.0" - petitparser: - dependency: transitive - description: - name: petitparser - sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790" - url: "https://pub.dev" - source: hosted - version: "7.1.0" - platform: - dependency: transitive - description: - name: platform - sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec - url: "https://pub.dev" - source: hosted - version: "3.2.0" - plugin_platform_interface: - dependency: transitive - description: - name: plugin_platform_interface - sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" - url: "https://pub.dev" - source: hosted - version: "2.1.8" - pointycastle: - dependency: transitive - description: - name: pointycastle - sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" - url: "https://pub.dev" - source: hosted - version: "3.9.1" - posix: - dependency: transitive - description: - name: posix - sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" - url: "https://pub.dev" - source: hosted - version: "6.5.4" - process: - dependency: transitive - description: - name: process - sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" - url: "https://pub.dev" - source: hosted - version: "5.0.6" - properties: - dependency: transitive - description: - name: properties - sha256: "333f427dd4ed07bdbe8c75b9ff864a1e70b5d7a8426a2e8bdd457b65ae5ac598" - url: "https://pub.dev" - source: hosted - version: "2.1.1" - pub_semver: - dependency: "direct main" - description: - name: pub_semver - sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" - url: "https://pub.dev" - source: hosted - version: "2.2.1" - record_use: - dependency: transitive - description: - name: record_use - sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" - url: "https://pub.dev" - source: hosted - version: "1.1.1" - rxdart: - dependency: transitive - description: - name: rxdart - sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" - url: "https://pub.dev" - source: hosted - version: "0.28.0" - safe_local_storage: - dependency: transitive - description: - name: safe_local_storage - sha256: "76288b689a3e1fddccb377177feed85d73fdfc64c9c3c52991e2d9aba35c4857" - url: "https://pub.dev" - source: hosted - version: "2.0.7" - screen_retriever: - dependency: transitive - description: - name: screen_retriever - sha256: ace919117a7520c13a50a6259e60c4a0d4cbe98809468792a91b5c5adada2aa6 - url: "https://pub.dev" - source: hosted - version: "0.2.2" - screen_retriever_linux: - dependency: transitive - description: - name: screen_retriever_linux - sha256: "7b52006a5ceae1f3d5af7f77188c3290d6e7d8ded16d99809bea84967c65c257" - url: "https://pub.dev" - source: hosted - version: "0.2.2" - screen_retriever_macos: - dependency: transitive - description: - name: screen_retriever_macos - sha256: a1489b99cce597c45a54b9aae1cd94c8d4705353b7e0bb2457a6e4de44e0ad8a - url: "https://pub.dev" - source: hosted - version: "0.2.2" - screen_retriever_platform_interface: - dependency: transitive - description: - name: screen_retriever_platform_interface - sha256: "94a5535277510a63184ca178ce12a1449bc0b38618879aa1c18bf57369c5064a" - url: "https://pub.dev" - source: hosted - version: "0.2.2" - screen_retriever_windows: - dependency: transitive - description: - name: screen_retriever_windows - sha256: dafc6922b0bfbf1d48cf3ccbf519b4fff47bdcb820da1728ea6db675fecc9324 - url: "https://pub.dev" - source: hosted - version: "0.2.2" - sentry: - dependency: transitive - description: - name: sentry - sha256: de233eb7a4d30e8fc18dafffde344b1846f92ffd079f454c56872e064145e396 - url: "https://pub.dev" - source: hosted - version: "10.3.0" - sentry_dart_plugin: - dependency: "direct dev" - description: - name: sentry_dart_plugin - sha256: da9c1d0b3c87a251bfc36301f16af090a88c2d59128fe9a6f908f5ac20340c97 - url: "https://pub.dev" - source: hosted - version: "3.4.0" - sentry_flutter: - dependency: "direct main" - description: - name: sentry_flutter - sha256: "798acb5d181869403828a0c0ac54989c9b1f7189efd13cc2a55102d18454bf23" - url: "https://pub.dev" - source: hosted - version: "10.3.0" - sky_engine: - dependency: transitive - description: flutter - source: sdk - version: "0.0.0" - source_span: - dependency: transitive - description: - name: source_span - sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" - url: "https://pub.dev" - source: hosted - version: "1.10.2" - sqflite: - dependency: transitive - description: - name: sqflite - sha256: "21a9750de2deb464946e9f41c7ddf176e25553618afdfc774868cd454990c06a" - url: "https://pub.dev" - source: hosted - version: "2.4.5" - sqflite_android: - dependency: transitive - description: - name: sqflite_android - sha256: "3986f4cbdde19ca538aae877981c5a53400dcc4601499df18e7ed9e848a0bdd4" - url: "https://pub.dev" - source: hosted - version: "2.4.5" - sqflite_common: - dependency: transitive - description: - name: sqflite_common - sha256: cf0cfe7c12786394bc20433ecb6d7ff3cf2c4e458dc075c1e56c8666d6a2deb4 - url: "https://pub.dev" - source: hosted - version: "2.5.15" - sqflite_darwin: - dependency: transitive - description: - name: sqflite_darwin - sha256: "5652e66a7db9996e8604b70b34b5876714b9dd1257f557041f718a153f995d28" - url: "https://pub.dev" - source: hosted - version: "2.4.5" - sqflite_platform_interface: - dependency: transitive - description: - name: sqflite_platform_interface - sha256: "5b611dbcb9bab33e7073594ecac111bf0a86ffc342652c2081160d7038a45fb6" - url: "https://pub.dev" - source: hosted - version: "2.4.3" - stack_trace: - dependency: transitive - description: - name: stack_trace - sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" - url: "https://pub.dev" - source: hosted - version: "1.12.2" - string_scanner: - dependency: transitive - description: - name: string_scanner - sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" - url: "https://pub.dev" - source: hosted - version: "1.4.1" - synchronized: - dependency: "direct main" - description: - name: synchronized - sha256: "0ce4712bd3be1fccfab14458059baebb400ba6c6239b65398e3464945fabbae7" - url: "https://pub.dev" - source: hosted - version: "3.6.1" - system_info2: - dependency: transitive - description: - name: system_info2 - sha256: "2d5e586c5e6b569d2e3afab1e61542d8fc0603be2d6ee671e573c041541a1541" - url: "https://pub.dev" - source: hosted - version: "4.2.0" - term_glyph: - dependency: transitive - description: - name: term_glyph - sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" - url: "https://pub.dev" - source: hosted - version: "1.2.2" - tray_manager: - dependency: "direct main" - description: - name: tray_manager - sha256: "4be089ac5fbca1c1724ea2b28a4827ff84f217956558d4eaf9441fd231c160a0" - url: "https://pub.dev" - source: hosted - version: "0.8.0" - typed_data: - dependency: transitive - description: - name: typed_data - sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 - url: "https://pub.dev" - source: hosted - version: "1.4.0" - universal_platform: - dependency: transitive - description: - name: universal_platform - sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec" - url: "https://pub.dev" - source: hosted - version: "1.1.0" - uri_parser: - dependency: transitive - description: - name: uri_parser - sha256: "051c62e5f693de98ca9f130ee707f8916e2266945565926be3ff20659f7853ce" - url: "https://pub.dev" - source: hosted - version: "3.0.2" - url_launcher: - dependency: "direct main" - description: - name: url_launcher - sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda - url: "https://pub.dev" - source: hosted - version: "6.3.3" - url_launcher_android: - dependency: transitive - description: - name: url_launcher_android - sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" - url: "https://pub.dev" - source: hosted - version: "6.3.33" - url_launcher_ios: - dependency: transitive - description: - name: url_launcher_ios - sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" - url: "https://pub.dev" - source: hosted - version: "6.4.2" - url_launcher_linux: - dependency: transitive - description: - name: url_launcher_linux - sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" - url: "https://pub.dev" - source: hosted - version: "3.2.3" - url_launcher_macos: - dependency: transitive - description: - name: url_launcher_macos - sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" - url: "https://pub.dev" - source: hosted - version: "3.2.6" - url_launcher_platform_interface: - dependency: transitive - description: - name: url_launcher_platform_interface - sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" - url: "https://pub.dev" - source: hosted - version: "2.3.2" - url_launcher_web: - dependency: transitive - description: - name: url_launcher_web - sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" - url: "https://pub.dev" - source: hosted - version: "2.4.3" - url_launcher_windows: - dependency: transitive - description: - name: url_launcher_windows - sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" - url: "https://pub.dev" - source: hosted - version: "3.1.6" - uuid: - dependency: "direct main" - description: - name: uuid - sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" - url: "https://pub.dev" - source: hosted - version: "4.6.0" - vector_math: - dependency: transitive - description: - name: vector_math - sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc - url: "https://pub.dev" - source: hosted - version: "2.4.4" - watcher: - dependency: transitive - description: - name: watcher - sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" - url: "https://pub.dev" - source: hosted - version: "1.2.1" - web: - dependency: transitive - description: - name: web - sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b - url: "https://pub.dev" - source: hosted - version: "1.1.2" - win32: - dependency: "direct main" - description: - name: win32 - sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d - url: "https://pub.dev" - source: hosted - version: "6.4.0" - win32_registry: - dependency: transitive - description: - name: win32_registry - sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" - url: "https://pub.dev" - source: hosted - version: "3.0.3" - window_manager: - dependency: "direct main" - description: - name: window_manager - sha256: "7eb6d6c4164ec08e1bf978d6e733f3cebe792e2a23fb07cbca25c2872bfdbdcd" - url: "https://pub.dev" - source: hosted - version: "0.5.1" - windows_file_picker: - dependency: transitive - description: - name: windows_file_picker - sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072" - url: "https://pub.dev" - source: hosted - version: "2.0.1" - xdg_directories: - dependency: transitive - description: - name: xdg_directories - sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" - url: "https://pub.dev" - source: hosted - version: "1.1.0" - xml: - dependency: transitive - description: - name: xml - sha256: "0fe8cc98946def31cbcbc8734aa4067031e6f65ea3a78a508060bfed2200bfeb" - url: "https://pub.dev" - source: hosted - version: "7.1.0" - yaml: - dependency: transitive - description: - name: yaml - sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea - url: "https://pub.dev" - source: hosted - version: "3.1.4" -sdks: - dart: ">=3.13.7 <4.0.0" - flutter: ">=3.47.9" +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "1c5591cc6f252d5f440d96ab87c03e43504be552a3fa49d7cb7563f04c51fb0a" + url: "https://pub.dev" + source: hosted + version: "111.0.0" + analyzer: + dependency: "direct dev" + description: + name: analyzer + sha256: "6c39bd5486a310e56217bed7cb1691377959f31be4227e41750107db7e6dd55c" + url: "https://pub.dev" + source: hosted + version: "14.7.0" + android_file_picker: + dependency: transitive + description: + name: android_file_picker + sha256: "868183c959e754e915954d8074c20cfa4cfdb4684b35ecc08378437be1a542d8" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + ansicolor: + dependency: transitive + description: + name: ansicolor + sha256: "50e982d500bc863e1d703448afdbf9e5a72eb48840a4f766fa361ffd6877055f" + url: "https://pub.dev" + source: hosted + version: "2.0.3" + archive: + dependency: "direct main" + description: + name: archive + sha256: de5ac590b8155e4e676088d714bd41ea620449a6adc0f7950c5073874b287ddb + url: "https://pub.dev" + source: hosted + version: "4.6.0" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + asn1lib: + dependency: transitive + description: + name: asn1lib + sha256: cfb3cf6a53158918d52dda61bc26f0cc8612a0d3b9dc29e87eaa3423902ca636 + url: "https://pub.dev" + source: hosted + version: "1.6.8" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + audio_service: + dependency: "direct main" + description: + name: audio_service + sha256: "95f3267f3449eb5cf71c8fcf1d556f57af1e898e2dc5815fb168d1843653edb7" + url: "https://pub.dev" + source: hosted + version: "0.18.19" + audio_service_platform_interface: + dependency: "direct main" + description: + name: audio_service_platform_interface + sha256: "6283782851f6c8b501b60904a32fc7199dc631172da0629d7301e66f672ab777" + url: "https://pub.dev" + source: hosted + version: "0.1.3" + audio_service_web: + dependency: transitive + description: + name: audio_service_web + sha256: b8ea9243201ee53383157fbccf13d5d2a866b5dda922ec19d866d1d5d70424df + url: "https://pub.dev" + source: hosted + version: "0.1.4" + audio_session: + dependency: "direct main" + description: + name: audio_session + sha256: f9e7711a0e24ca8b40f5d7ac374c3c6e55016f3157912badd18199cdbbca5c4d + url: "https://pub.dev" + source: hosted + version: "0.2.4" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + cnativeapi: + dependency: transitive + description: + name: cnativeapi + sha256: c43703998995e132b0656d2b8a95ed2bedc6b22ccee2c827bcdc075e0330e319 + url: "https://pub.dev" + source: hosted + version: "0.5.10" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "1ef22a0be3af9370bd9481ac76db114db92bfe75d5ca2b2d7bc911764478a4d9" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4 + url: "https://pub.dev" + source: hosted + version: "3.0.8" + cupertino_ui: + dependency: transitive + description: + name: cupertino_ui + sha256: "369e39a1c5c030a6212589c3da1809920b1c2cfade7b02aade7695bfa4b88c3a" + url: "https://pub.dev" + source: hosted + version: "1.1.6" + dbus: + dependency: transitive + description: + name: dbus + sha256: f7db8504e715b835f5ebe5fe74604ccd961d504c73389a5d8e81bafc2e2f3612 + url: "https://pub.dev" + source: hosted + version: "0.8.0" + device_info_plus: + dependency: "direct main" + description: + name: device_info_plus + sha256: ade1c36f8355d6284c98e4a47992ea263887ed3d1acb281e37635dd45f04c4aa + url: "https://pub.dev" + source: hosted + version: "13.3.0" + device_info_plus_platform_interface: + dependency: transitive + description: + name: device_info_plus_platform_interface + sha256: "04b173a92e2d9161dfead145667037c8d834db725ce2e7b942bfe18fd2f45a46" + url: "https://pub.dev" + source: hosted + version: "8.1.0" + dio: + dependency: "direct main" + description: + name: dio + sha256: "852ec3b48cc431ac04fff978413c541502b67ffc3e26921e74e3d994694192c1" + url: "https://pub.dev" + source: hosted + version: "5.11.1" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "3a1b2cd7be71086f38504956e3ebcd2837288d231ff454bafa78021244102bfc" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + encrypt: + dependency: "direct main" + description: + name: encrypt + sha256: "62d9aa4670cc2a8798bab89b39fc71b6dfbacf615de6cf5001fb39f7e4a996a2" + url: "https://pub.dev" + source: hosted + version: "5.0.3" + ffi: + dependency: "direct main" + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_picker: + dependency: "direct main" + description: + name: file_picker + sha256: c64036857780d7125f011d543f89eedcb5df61da473668bace4eee9ab875284d + url: "https://pub.dev" + source: hosted + version: "13.3.2" + file_picker_darwin: + dependency: transitive + description: + name: file_picker_darwin + sha256: daeb0219f6279c73eb9c63ae9a566beef04ae13d59b8feba0be2a7f3b258d3d4 + url: "https://pub.dev" + source: hosted + version: "2.4.2" + file_picker_linux: + dependency: transitive + description: + name: file_picker_linux + sha256: eb00de71b123e91d3c61f389a05b8cc90f9cbe7e4c88da30ebe2f0442b281b61 + url: "https://pub.dev" + source: hosted + version: "2.0.3" + file_picker_platform_interface: + dependency: transitive + description: + name: file_picker_platform_interface + sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + file_picker_web: + dependency: transitive + description: + name: file_picker_web + sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c + url: "https://pub.dev" + source: hosted + version: "4.2.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_cache_manager: + dependency: transitive + description: + name: flutter_cache_manager + sha256: a42024cf8bbb7e1f4d2875301660f62543601a4c3b20119ea9a683e4d191d0f4 + url: "https://pub.dev" + source: hosted + version: "3.5.0" + flutter_inappwebview: + dependency: "direct main" + description: + name: flutter_inappwebview + sha256: "80092d13d3e29b6227e25b67973c67c7210bd5e35c4b747ca908e31eb71a46d5" + url: "https://pub.dev" + source: hosted + version: "6.1.5" + flutter_inappwebview_android: + dependency: transitive + description: + name: flutter_inappwebview_android + sha256: "62557c15a5c2db5d195cb3892aab74fcaec266d7b86d59a6f0027abd672cddba" + url: "https://pub.dev" + source: hosted + version: "1.1.3" + flutter_inappwebview_internal_annotations: + dependency: transitive + description: + name: flutter_inappwebview_internal_annotations + sha256: e30fba942e3debea7b7e6cdd4f0f59ce89dd403a9865193e3221293b6d1544c6 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + flutter_inappwebview_ios: + dependency: transitive + description: + name: flutter_inappwebview_ios + sha256: "5818cf9b26cf0cbb0f62ff50772217d41ea8d3d9cc00279c45f8aabaa1b4025d" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_macos: + dependency: transitive + description: + name: flutter_inappwebview_macos + sha256: c1fbb86af1a3738e3541364d7d1866315ffb0468a1a77e34198c9be571287da1 + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_platform_interface: + dependency: transitive + description: + name: flutter_inappwebview_platform_interface + sha256: cf5323e194096b6ede7a1ca808c3e0a078e4b33cc3f6338977d75b4024ba2500 + url: "https://pub.dev" + source: hosted + version: "1.3.0+1" + flutter_inappwebview_web: + dependency: transitive + description: + name: flutter_inappwebview_web + sha256: "55f89c83b0a0d3b7893306b3bb545ba4770a4df018204917148ebb42dc14a598" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + flutter_inappwebview_windows: + dependency: transitive + description: + name: flutter_inappwebview_windows + sha256: "8b4d3a46078a2cdc636c4a3d10d10f2a16882f6be607962dbfff8874d1642055" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 + url: "https://pub.dev" + source: hosted + version: "11.2.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 + url: "https://pub.dev" + source: hosted + version: "0.4.3" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + url: "https://pub.dev" + source: hosted + version: "4.2.2" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + get: + dependency: "direct main" + description: + name: get + sha256: "5ed34a7925b85336e15d472cc4cfe7d9ebf4ab8e8b9f688585bf6b50f4c3d79a" + url: "https://pub.dev" + source: hosted + version: "4.7.3" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + globbing: + dependency: transitive + description: + name: globbing + sha256: "4f89cfaf6fa74c9c1740a96259da06bd45411ede56744e28017cc534a12b6e2d" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f + url: "https://pub.dev" + source: hosted + version: "2.2.0" + http: + dependency: transitive + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + injector: + dependency: transitive + description: + name: injector + sha256: ed389bed5b48a699d5b9561c985023d0d5cc88dd5ff2237aadcce5a5ab433e4e + url: "https://pub.dev" + source: hosted + version: "3.0.0" + intl: + dependency: transitive + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" + jni: + dependency: transitive + description: + name: jni + sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c" + url: "https://pub.dev" + source: hosted + version: "1.1.2" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + material_ui: + dependency: "direct main" + description: + name: material_ui + sha256: d9b4f6c69b80bc83d0a14357c86e4c14c8076e807ae73cf2960c8560f623995f + url: "https://pub.dev" + source: hosted + version: "1.0.0" + media_kit: + dependency: "direct main" + description: + name: media_kit + sha256: ae9e79597500c7ad6083a3c7b7b7544ddabfceacce7ae5c9709b0ec16a5d6643 + url: "https://pub.dev" + source: hosted + version: "1.2.6" + media_kit_libs_android_audio: + dependency: transitive + description: + name: media_kit_libs_android_audio + sha256: "8f8f9759e537e12d66f08bc4d5279eb1bb21a0ccc519ff3442c68a9f3b6dd68b" + url: "https://pub.dev" + source: hosted + version: "1.3.8" + media_kit_libs_audio: + dependency: "direct main" + description: + name: media_kit_libs_audio + sha256: "81bf506c234e81e3ec536ba72f8f700a928543c14c345220210cae0411636316" + url: "https://pub.dev" + source: hosted + version: "1.0.7" + media_kit_libs_ios_audio: + dependency: transitive + description: + name: media_kit_libs_ios_audio + sha256: "78ccf04e27d6b4ba00a355578ccb39b772f00d48269a6ac3db076edf2d51934f" + url: "https://pub.dev" + source: hosted + version: "1.1.4" + media_kit_libs_linux: + dependency: transitive + description: + name: media_kit_libs_linux + sha256: "2b473399a49ec94452c4d4ae51cfc0f6585074398d74216092bf3d54aac37ecf" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + media_kit_libs_macos_audio: + dependency: transitive + description: + name: media_kit_libs_macos_audio + sha256: "3be21844df98f286de32808592835073cdef2c1a10078bac135da790badca950" + url: "https://pub.dev" + source: hosted + version: "1.1.4" + media_kit_libs_windows_audio: + dependency: transitive + description: + name: media_kit_libs_windows_audio + sha256: c2fd558cc87b9d89a801141fcdffe02e338a3b21a41a18fbd63d5b221a1b8e53 + url: "https://pub.dev" + source: hosted + version: "1.0.9" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "120b6fc66acd8a5ddeaeb1e59b78836bb3ec9919bd9d9dfb1e2401985710c2c0" + url: "https://pub.dev" + source: hosted + version: "0.19.6" + nativeapi: + dependency: transitive + description: + name: nativeapi + sha256: "118045bb549cb6fabad472a3a22a537e7310bbf20097350f5027808b4a5853ce" + url: "https://pub.dev" + source: hosted + version: "0.5.10" + nativeapi_flutter: + dependency: transitive + description: + name: nativeapi_flutter + sha256: "357a405c69212f5157da1bd3be183a53c2b841d0de0eb51f4a3947913712aec4" + url: "https://pub.dev" + source: hosted + version: "0.5.10" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "322d5f1f0680534acaf557c5d68e97b40c3800ee5e15b63dcacc3c31504674c2" + url: "https://pub.dev" + source: hosted + version: "9.6.3" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" + url: "https://pub.dev" + source: hosted + version: "10.2.2" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.dev" + source: hosted + version: "4.1.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + petitparser: + dependency: transitive + description: + name: petitparser + sha256: "2f1564aadb14215e478563b5406cb80729d022158c01dc50c96013c2f7eb4790" + url: "https://pub.dev" + source: hosted + version: "7.1.0" + platform: + dependency: transitive + description: + name: platform + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec + url: "https://pub.dev" + source: hosted + version: "3.2.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: transitive + description: + name: pointycastle + sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" + url: "https://pub.dev" + source: hosted + version: "3.9.1" + posix: + dependency: transitive + description: + name: posix + sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63" + url: "https://pub.dev" + source: hosted + version: "6.5.4" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" + properties: + dependency: transitive + description: + name: properties + sha256: "333f427dd4ed07bdbe8c75b9ff864a1e70b5d7a8426a2e8bdd457b65ae5ac598" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + pub_semver: + dependency: "direct main" + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + rxdart: + dependency: transitive + description: + name: rxdart + sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" + url: "https://pub.dev" + source: hosted + version: "0.28.0" + safe_local_storage: + dependency: transitive + description: + name: safe_local_storage + sha256: "76288b689a3e1fddccb377177feed85d73fdfc64c9c3c52991e2d9aba35c4857" + url: "https://pub.dev" + source: hosted + version: "2.0.7" + screen_retriever: + dependency: transitive + description: + name: screen_retriever + sha256: ace919117a7520c13a50a6259e60c4a0d4cbe98809468792a91b5c5adada2aa6 + url: "https://pub.dev" + source: hosted + version: "0.2.2" + screen_retriever_linux: + dependency: transitive + description: + name: screen_retriever_linux + sha256: "7b52006a5ceae1f3d5af7f77188c3290d6e7d8ded16d99809bea84967c65c257" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + screen_retriever_macos: + dependency: transitive + description: + name: screen_retriever_macos + sha256: a1489b99cce597c45a54b9aae1cd94c8d4705353b7e0bb2457a6e4de44e0ad8a + url: "https://pub.dev" + source: hosted + version: "0.2.2" + screen_retriever_platform_interface: + dependency: transitive + description: + name: screen_retriever_platform_interface + sha256: "94a5535277510a63184ca178ce12a1449bc0b38618879aa1c18bf57369c5064a" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + screen_retriever_windows: + dependency: transitive + description: + name: screen_retriever_windows + sha256: dafc6922b0bfbf1d48cf3ccbf519b4fff47bdcb820da1728ea6db675fecc9324 + url: "https://pub.dev" + source: hosted + version: "0.2.2" + sentry: + dependency: transitive + description: + name: sentry + sha256: de233eb7a4d30e8fc18dafffde344b1846f92ffd079f454c56872e064145e396 + url: "https://pub.dev" + source: hosted + version: "10.3.0" + sentry_dart_plugin: + dependency: "direct dev" + description: + name: sentry_dart_plugin + sha256: da9c1d0b3c87a251bfc36301f16af090a88c2d59128fe9a6f908f5ac20340c97 + url: "https://pub.dev" + source: hosted + version: "3.4.0" + sentry_flutter: + dependency: "direct main" + description: + name: sentry_flutter + sha256: "798acb5d181869403828a0c0ac54989c9b1f7189efd13cc2a55102d18454bf23" + url: "https://pub.dev" + source: hosted + version: "10.3.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + sqflite: + dependency: transitive + description: + name: sqflite + sha256: "21a9750de2deb464946e9f41c7ddf176e25553618afdfc774868cd454990c06a" + url: "https://pub.dev" + source: hosted + version: "2.4.5" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "3986f4cbdde19ca538aae877981c5a53400dcc4601499df18e7ed9e848a0bdd4" + url: "https://pub.dev" + source: hosted + version: "2.4.5" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + sha256: cf0cfe7c12786394bc20433ecb6d7ff3cf2c4e458dc075c1e56c8666d6a2deb4 + url: "https://pub.dev" + source: hosted + version: "2.5.15" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "5652e66a7db9996e8604b70b34b5876714b9dd1257f557041f718a153f995d28" + url: "https://pub.dev" + source: hosted + version: "2.4.5" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "5b611dbcb9bab33e7073594ecac111bf0a86ffc342652c2081160d7038a45fb6" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + synchronized: + dependency: "direct main" + description: + name: synchronized + sha256: "0ce4712bd3be1fccfab14458059baebb400ba6c6239b65398e3464945fabbae7" + url: "https://pub.dev" + source: hosted + version: "3.6.1" + system_info2: + dependency: transitive + description: + name: system_info2 + sha256: "2d5e586c5e6b569d2e3afab1e61542d8fc0603be2d6ee671e573c041541a1541" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + tray_manager: + dependency: "direct main" + description: + name: tray_manager + sha256: "4be089ac5fbca1c1724ea2b28a4827ff84f217956558d4eaf9441fd231c160a0" + url: "https://pub.dev" + source: hosted + version: "0.8.0" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + universal_platform: + dependency: transitive + description: + name: universal_platform + sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + uri_parser: + dependency: transitive + description: + name: uri_parser + sha256: "051c62e5f693de98ca9f130ee707f8916e2266945565926be3ff20659f7853ce" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + url_launcher: + dependency: "direct main" + description: + name: url_launcher + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "611e87fb320b70d1dd721dc46af89c98aceccea9b31fde49e084591414e0c610" + url: "https://pub.dev" + source: hosted + version: "6.3.33" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: fa49e1674cb84acb900141714e6c6e1f9ae099827c24d141430ff6819db4e1bc + url: "https://pub.dev" + source: hosted + version: "2.4.4" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + win32: + dependency: "direct main" + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + win32_registry: + dependency: transitive + description: + name: win32_registry + sha256: "73b1d78920a9d6e03f8b4e43e612b87bf3152a0e5c5e5150267762b7c4116904" + url: "https://pub.dev" + source: hosted + version: "3.0.3" + window_manager: + dependency: "direct main" + description: + name: window_manager + sha256: "7eb6d6c4164ec08e1bf978d6e733f3cebe792e2a23fb07cbca25c2872bfdbdcd" + url: "https://pub.dev" + source: hosted + version: "0.5.1" + windows_file_picker: + dependency: transitive + description: + name: windows_file_picker + sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072" + url: "https://pub.dev" + source: hosted + version: "2.0.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + xml: + dependency: transitive + description: + name: xml + sha256: "0fe8cc98946def31cbcbc8734aa4067031e6f65ea3a78a508060bfed2200bfeb" + url: "https://pub.dev" + source: hosted + version: "7.1.0" + xmplus_android_background: + dependency: "direct main" + description: + path: "packages/xmplus_android_background" + relative: true + source: path + version: "1.0.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.13.7 <4.0.0" + flutter: ">=3.47.9" diff --git a/pubspec.yaml b/pubspec.yaml index 2aef55b..4697aa7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,69 +1,71 @@ -name: xmly_flutter -description: XMPlus 下载与收听客户端 -publish_to: none -version: 1.2.2+15 -environment: - sdk: '>=3.13.7 <4.0.0' - flutter: '>=3.47.9' -dependencies: - flutter: - sdk: flutter - flutter_localizations: - sdk: flutter - material_ui: 1.0.0 - get: 4.7.3 - dio: ^5.9.1 - crypto: ^3.0.6 - encrypt: ^5.0.3 - archive: ^4.0.0 - file_picker: ^13.1.0 - path: ^1.9.1 - path_provider: ^2.1.5 - synchronized: ^3.3.0 - uuid: ^4.5.1 - media_kit: 1.2.6 - media_kit_libs_audio: 1.0.7 - audio_service: ^0.18.19 - audio_service_platform_interface: ^0.1.3 - audio_session: ^0.2.4 - flutter_inappwebview: 6.1.5 - flutter_secure_storage: 11.2.0 - window_manager: 0.5.1 - tray_manager: 0.8.0 - win32: ^6.3.0 - ffi: ^2.2.0 - package_info_plus: ^10.2.2 - url_launcher: ^6.3.3 - pub_semver: ^2.2.1 - device_info_plus: ^13.3.0 - sentry_flutter: 10.3.0 -dev_dependencies: - sentry_dart_plugin: 3.4.0 - analyzer: 14.7.0 -sentry: - org: tkstudio - project: xmplus - upload_debug_symbols: true - upload_sources: false - upload_source_maps: false - wait_for_processing: true -flutter: - uses-material-design: true - assets: - - assets/branding/xmplus.png - - windows/runner/resources/app_icon.ico - - LICENSE - - NOTICE - - windows/LICENSE.PiliPlus - - licenses/android/THIRD-PARTY-NOTICES.txt - - licenses/media/THIRD-PARTY-NOTICES.txt - - licenses/fonts/HarmonyOS_Sans_SC_LICENSE.txt - fonts: - - family: HarmonyOS Sans SC - fonts: - - asset: assets/fonts/HarmonyOS_Sans_SC_Regular.ttf - weight: 400 - - asset: assets/fonts/HarmonyOS_Sans_SC_Medium.ttf - weight: 500 - - asset: assets/fonts/HarmonyOS_Sans_SC_Bold.ttf - weight: 700 +name: xmly_flutter +description: XMPlus 下载与收听客户端 +publish_to: none +version: 1.2.3+16 +environment: + sdk: '>=3.13.7 <4.0.0' + flutter: '>=3.47.9' +dependencies: + flutter: + sdk: flutter + flutter_localizations: + sdk: flutter + material_ui: 1.0.0 + get: 4.7.3 + dio: ^5.9.1 + crypto: ^3.0.6 + encrypt: ^5.0.3 + archive: ^4.0.0 + file_picker: ^13.1.0 + path: ^1.9.1 + path_provider: ^2.1.5 + synchronized: ^3.3.0 + uuid: ^4.5.1 + media_kit: 1.2.6 + media_kit_libs_audio: 1.0.7 + audio_service: ^0.18.19 + audio_service_platform_interface: ^0.1.3 + audio_session: ^0.2.4 + flutter_inappwebview: 6.1.5 + flutter_secure_storage: 11.2.0 + window_manager: 0.5.1 + tray_manager: 0.8.0 + win32: ^6.3.0 + ffi: ^2.2.0 + package_info_plus: ^10.2.2 + url_launcher: ^6.3.3 + pub_semver: ^2.2.1 + device_info_plus: ^13.3.0 + sentry_flutter: 10.3.0 + xmplus_android_background: + path: packages/xmplus_android_background +dev_dependencies: + sentry_dart_plugin: 3.4.0 + analyzer: 14.7.0 +sentry: + org: tkstudio + project: xmplus + upload_debug_symbols: true + upload_sources: false + upload_source_maps: false + wait_for_processing: true +flutter: + uses-material-design: true + assets: + - assets/branding/xmplus.png + - windows/runner/resources/app_icon.ico + - LICENSE + - NOTICE + - windows/LICENSE.PiliPlus + - licenses/android/THIRD-PARTY-NOTICES.txt + - licenses/media/THIRD-PARTY-NOTICES.txt + - licenses/fonts/HarmonyOS_Sans_SC_LICENSE.txt + fonts: + - family: HarmonyOS Sans SC + fonts: + - asset: assets/fonts/HarmonyOS_Sans_SC_Regular.ttf + weight: 400 + - asset: assets/fonts/HarmonyOS_Sans_SC_Medium.ttf + weight: 500 + - asset: assets/fonts/HarmonyOS_Sans_SC_Bold.ttf + weight: 700 diff --git a/tool/check_method_trace.dart b/tool/check_method_trace.dart index 53aa30a..f8b7f77 100644 --- a/tool/check_method_trace.dart +++ b/tool/check_method_trace.dart @@ -11,6 +11,18 @@ const traceExclusions = { 'Sentry transport: prevent trace recursion', }; +// These per-node traversals are covered by storage operation traces. Keep this +// list narrow: adding a recursive trace here can stall startup on large profiles. +const traceHotspots = { + 'lib/storage/app_storage.dart::AppStorage._validate.closure#1', + 'lib/storage/app_storage.dart::AppStorage._validate.inspect', + 'lib/storage/app_storage.dart::AppStorage._validate.closure#3', + 'lib/storage/app_storage.dart::AppStorage._validate.closure#4', + 'lib/storage/app_storage.dart::AppStorage._freezeMap', + 'lib/storage/app_storage.dart::AppStorage._freezeMap.closure#1', + 'lib/storage/app_storage.dart::AppStorage._freeze', +}; + /// One source body, shared with the disposable AST instrumenter. class TraceBody { final FunctionBody body; @@ -69,19 +81,15 @@ TraceScan scanMethodTrace(CompilationUnit unit, String path) { final seen = {}; for (final body in collector.bodies) { if (!seen.add(body)) continue; - final reason = _exemption(body); + final identity = '$path::${identities.symbol(body.parent!)}'; + final reason = traceHotspots.contains(identity) + ? 'storage per-node traversal (covered by operation traces)' + : _exemption(body); if (reason != null) exemptions.update(reason, (n) => n + 1, ifAbsent: () => 1); final entries = _TraceEntries(body); body.accept(entries); - bodies.add( - TraceBody( - body, - '$path::${identities.symbol(body.parent!)}', - reason, - entries.entries, - ), - ); + bodies.add(TraceBody(body, identity, reason, entries.entries)); } for (final type in collector.classes) { // Implicit constructors have no source body and must not be synthesized.