From 61da0ee29718f87b141496f5913328c51ace3d1c Mon Sep 17 00:00:00 2001
From: teikengstudio <337756906+teikengstudio@users.noreply.github.com>
Date: Tue, 17 Nov 2026 01:59:01 +0800
Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=B8=8B=E8=BD=BD?=
=?UTF-8?q?=E4=B8=8E=E5=88=86=E9=A1=B5=E5=BC=82=E5=B8=B8=E5=B9=B6=E5=87=86?=
=?UTF-8?q?=E5=A4=87=201.2.3?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 修复下载列表、启动日志、订阅与评论分页及下架内容处理。
- 修复 Android 音频文件授权和前台下载插件,完善平滑预测性返回。
- 完成真实账号只读验证和 Flutter 实际帧验收;未包含临时测试或账号数据。
---
CHANGELOG.md | 8 +
android/app/src/main/AndroidManifest.xml | 9 +-
.../teikengstudio/xmplus/MainActivity.kt | 113 +-
.../xmplus/SharedAudioProvider.kt | 78 +
lib/api/xmly_client.dart | 7 +
lib/api/xmly_comments.dart | 38 +-
lib/api/xmly_experience.dart | 9 +-
lib/app.dart | 173 +-
lib/common/theme.dart | 1199 +--
lib/pages/album_reviews_page.dart | 53 +-
lib/pages/download_page.dart | 6395 +++++++++--------
lib/pages/player_panel.dart | 5682 ++++++++-------
lib/pages/startup_page.dart | 667 +-
lib/services/app_log.dart | 2846 ++++----
lib/services/auto_download_service.dart | 1154 +--
lib/services/download_service.dart | 11 +
lib/storage/app_storage.dart | 1323 ++--
.../android/build.gradle.kts | 21 +
.../android/src/main/AndroidManifest.xml | 8 +
.../background/DownloadBackgroundPlugin.kt | 158 +
.../background}/DownloadForegroundService.kt | 5 +-
.../res/drawable/ic_download_notification.xml | 0
.../xmplus_android_background/pubspec.yaml | 16 +
pubspec.lock | 2363 +++---
pubspec.yaml | 140 +-
tool/check_method_trace.dart | 26 +-
26 files changed, 11640 insertions(+), 10862 deletions(-)
create mode 100644 android/app/src/main/kotlin/teikengstudio/xmplus/SharedAudioProvider.kt
create mode 100644 packages/xmplus_android_background/android/build.gradle.kts
create mode 100644 packages/xmplus_android_background/android/src/main/AndroidManifest.xml
create mode 100644 packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background/DownloadBackgroundPlugin.kt
rename {android/app/src/main/kotlin/teikengstudio/xmplus => packages/xmplus_android_background/android/src/main/kotlin/teikengstudio/xmplus/background}/DownloadForegroundService.kt (96%)
rename {android/app => packages/xmplus_android_background/android}/src/main/res/drawable/ic_download_notification.xml (100%)
create mode 100644 packages/xmplus_android_background/pubspec.yaml
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