From cbb26873e88a7a13e868448c1cc578ce70b8c6ae Mon Sep 17 00:00:00 2001
From: 905086 <k2049@qq.com>
Date: Mon, 09 Nov 2026 10:54:51 +0800
Subject: [PATCH] feat: 新增客户端版本管理与下载页,重构配置加载方式

---
 fluttergamebox/lib/widgets/download_manager.dart |  614 ++++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 491 insertions(+), 123 deletions(-)

diff --git a/fluttergamebox/lib/widgets/download_manager.dart b/fluttergamebox/lib/widgets/download_manager.dart
index fbdf17c..06583df 100644
--- a/fluttergamebox/lib/widgets/download_manager.dart
+++ b/fluttergamebox/lib/widgets/download_manager.dart
@@ -1,9 +1,10 @@
 import 'dart:io';
 
+import 'package:file_picker/file_picker.dart';
 import 'package:flutter/material.dart';
-import 'package:fluttergamebox/api/api_client.dart';
 import 'package:fluttergamebox/common/theme.dart';
 import 'package:fluttergamebox/store/app_state.dart';
+import 'package:fluttergamebox/utils/network_info.dart';
 import 'package:fluttergamebox/utils/util.dart';
 import 'package:path/path.dart' as p;
 
@@ -16,9 +17,81 @@
   );
 }
 
-class _DownloadDialog extends StatelessWidget {
+class _DownloadDialog extends StatefulWidget {
   const _DownloadDialog();
   @override
+  State<_DownloadDialog> createState() => _DownloadDialogState();
+}
+
+class _DownloadDialogState extends State<_DownloadDialog> {
+  bool _showDetails = true; // 展开/收起详细任务
+  String _isp = '获取中...'; // 网络运营商(真实获取)
+  final _logCtrl = ScrollController(); // 解压日志自动滚动到底部
+
+  @override
+  void initState() {
+    super.initState();
+    _loadIsp();
+  }
+
+  /// 获取真实网络运营商
+  Future<void> _loadIsp() async {
+    try {
+      final n = await getNetworkInfo();
+      if (mounted) setState(() => _isp = n.isp);
+    } catch (_) {
+      if (mounted) setState(() => _isp = '未知');
+    }
+  }
+
+  @override
+  void dispose() {
+    _logCtrl.dispose();
+    super.dispose();
+  }
+
+  /// 安装完成后启动游戏
+  Future<void> _launchGame(DownloadTask task) async {
+    final ok = await launchInstalledGame(task.title, task.launchExe);
+    if (!ok && mounted) {
+      _toast(task.isTool ? '未找到工具文件,请重新下载安装' : '未找到游戏文件,请重新下载安装');
+    }
+  }
+
+  void _toast(String msg) {
+    final overlay = Overlay.of(context);
+    final entry = OverlayEntry(
+      builder: (context) => Positioned(
+        top: 60,
+        left: MediaQuery.of(context).size.width / 2 - 140,
+        child: Material(
+          color: Colors.transparent,
+          child: Container(
+            width: 280,
+            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+            decoration: BoxDecoration(
+              color: AppColors.red,
+              borderRadius: BorderRadius.circular(6),
+            ),
+            child: Row(
+              children: [
+                const Icon(Icons.error_outline, color: Colors.white, size: 18),
+                const SizedBox(width: 8),
+                Expanded(
+                  child: Text(msg,
+                      style: const TextStyle(color: Colors.white, fontSize: 13)),
+                ),
+              ],
+            ),
+          ),
+        ),
+      ),
+    );
+    overlay.insert(entry);
+    Future.delayed(const Duration(seconds: 2), () => entry.remove());
+  }
+
+  @override
   Widget build(BuildContext context) {
     return AnimatedBuilder(
       animation: DownloadManager.instance,
@@ -43,6 +116,15 @@
             ),
           );
         }
+        // 环形进度:下载阶段用下载进度,安装(解压)阶段用解压进度
+        final displayProgress = task.extracting ? task.extractProgress : task.progress;
+        if (task.extracting) {
+          WidgetsBinding.instance.addPostFrameCallback((_) {
+            if (_logCtrl.hasClients) {
+              _logCtrl.jumpTo(_logCtrl.position.maxScrollExtent);
+            }
+          });
+        }
         return Dialog(
           backgroundColor: const Color(0xFF1E2130),
           shape:
@@ -110,7 +192,7 @@
                             width: 86,
                             height: 86,
                             child: CircularProgressIndicator(
-                              value: task.finished ? 1 : task.progress,
+                              value: task.finished ? 1 : displayProgress,
                               color: task.paused
                                   ? AppColors.yellow
                                   : AppColors.accent,
@@ -119,7 +201,7 @@
                             ),
                           ),
                           Text(
-                            '${(task.progress * 100).toStringAsFixed(task.progress < 0.1 ? 2 : 0)}%',
+                            '${(displayProgress * 100).toStringAsFixed(displayProgress < 0.1 ? 2 : 0)}%',
                             style: const TextStyle(
                                 color: Colors.white,
                                 fontSize: 15,
@@ -137,7 +219,7 @@
                             children: [
                               Text(
                                 task.extracting
-                                    ? '正在解压安装...'
+                                    ? '正在安装'
                                     : task.extractFailed
                                         ? '解压失败'
                                         : task.finished
@@ -160,11 +242,9 @@
                           ),
                           const SizedBox(height: 8),
                           Text(
-                            task.extracting
-                                ? '解压中,请勿关闭软件'
-                                : task.extractFailed
-                                    ? '压缩包保留在下载目录,可手动解压'
-                                    : '${formatBytes(task.speed)}/s',
+                            task.extractFailed
+                                ? '压缩包保留在下载目录,可手动解压'
+                                : formatSpeed(task.speed),
                             style: const TextStyle(
                                 color: AppColors.textGray, fontSize: 13),
                           ),
@@ -176,9 +256,11 @@
                           ),
                           const SizedBox(height: 4),
                           Text(
-                            task.finished
-                                ? '已完成'
-                                : '剩余时间 ${formatDuration(task.etaSeconds)}',
+                            task.extracting
+                                ? '00:00:00'
+                                : task.finished
+                                    ? '已完成'
+                                    : '剩余时间 ${formatDuration(task.etaSeconds)}',
                             style: const TextStyle(
                                 color: AppColors.textGray, fontSize: 13),
                           ),
@@ -188,103 +270,157 @@
                   ],
                 ),
                 const SizedBox(height: 16),
-                // 网络信息条
+                // 网络信息条 + 收起详细任务
                 Container(
-                  padding:
-                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
-                  decoration: BoxDecoration(
-                    color: AppColors.bg,
-                    borderRadius: BorderRadius.circular(4),
+              padding:
+                  const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
+              decoration: BoxDecoration(
+                color: AppColors.bg,
+                borderRadius: BorderRadius.circular(4),
+              ),
+              child: Row(
+                children: [
+                  Text('网络运营商:$_isp',
+                      style: const TextStyle(
+                          color: AppColors.textGray, fontSize: 12)),
+                  const Spacer(),
+                  GestureDetector(
+                    onTap: () =>
+                        setState(() => _showDetails = !_showDetails),
+                    child: Row(
+                      children: [
+                        Text(
+                            _showDetails ? '收起详细任务' : '展开详细任务',
+                            style: const TextStyle(
+                                color: AppColors.textGray, fontSize: 12)),
+                        const SizedBox(width: 4),
+                        Icon(
+                            _showDetails
+                                ? Icons.keyboard_arrow_up
+                                : Icons.keyboard_arrow_down,
+                            color: AppColors.textGray,
+                            size: 14),
+                      ],
+                    ),
                   ),
-                  child: Row(
-                    children: [
-                      const Text('网络运营商:联通',
-                          style: TextStyle(
-                              color: AppColors.textGray, fontSize: 12)),
-                      const Spacer(),
-                      const Text('点击切换线路:自动',
-                          style: TextStyle(
-                              color: AppColors.textGray, fontSize: 12)),
-                    ],
+                  const SizedBox(width: 16),
+                  const Text('点击切换线路:自动',
+                      style: TextStyle(
+                          color: AppColors.textGray, fontSize: 12)),
+                ],
+              ),
+            ),
+                if (_showDetails) ...[
+                  const SizedBox(height: 10),
+                  // 详细任务列表:下载阶段显示分卷下载,安装阶段显示解压日志
+                  Container(
+                    constraints: const BoxConstraints(maxHeight: 180),
+                    decoration: BoxDecoration(
+                      color: AppColors.bg,
+                      borderRadius: BorderRadius.circular(4),
+                    ),
+                    child: task.extracting || task.extractFailed
+                        ? ListView.builder(
+                            shrinkWrap: true,
+                            controller: _logCtrl,
+                            itemCount: task.extractLog.length,
+                            itemBuilder: (context, i) {
+                              final e = task.extractLog[i];
+                              return Padding(
+                                padding: const EdgeInsets.symmetric(
+                                    horizontal: 12, vertical: 6),
+                                child: Row(
+                                  children: [
+                                    SizedBox(
+                                      width: 40,
+                                      child: Text('${e.percent}%',
+                                          style: const TextStyle(
+                                              color: AppColors.textWhite,
+                                              fontSize: 11)),
+                                    ),
+                                    Expanded(
+                                      child: Text(e.path,
+                                          maxLines: 1,
+                                          overflow: TextOverflow.ellipsis,
+                                          style: const TextStyle(
+                                              color: AppColors.textGray,
+                                              fontSize: 11)),
+                                    ),
+                                  ],
+                                ),
+                              );
+                            },
+                          )
+                        : ListView.builder(
+                            shrinkWrap: true,
+                            itemCount: task.files.length,
+                            itemBuilder: (context, i) {
+                              final f = task.files[i];
+                              Color stColor = AppColors.textDim;
+                              String stLabel = '等待下载';
+                              switch (f.status) {
+                                case DownloadStatus.preparing:
+                                  stColor = AppColors.yellow;
+                                  stLabel = '正在准备';
+                                case DownloadStatus.downloading:
+                                  stColor = AppColors.green;
+                                  stLabel = '正在下载';
+                                case DownloadStatus.paused:
+                                  stColor = AppColors.yellow;
+                                  stLabel = '已暂停';
+                                case DownloadStatus.done:
+                                  stColor = AppColors.green;
+                                  stLabel = '已完成';
+                                case DownloadStatus.failed:
+                                  stColor = AppColors.red;
+                                  stLabel = '下载失败';
+                                default:
+                                  stLabel = '等待下载';
+                              }
+                              return Padding(
+                                padding: const EdgeInsets.symmetric(
+                                    horizontal: 12, vertical: 6),
+                                child: Row(
+                                  children: [
+                                    SizedBox(
+                                      width: 200,
+                                      child: Text(f.name,
+                                          maxLines: 1,
+                                          overflow: TextOverflow.ellipsis,
+                                          style: const TextStyle(
+                                              color: AppColors.textWhite,
+                                              fontSize: 12)),
+                                    ),
+                                    Expanded(
+                                      child: LinearProgressIndicator(
+                                        value: f.progress,
+                                        backgroundColor: AppColors.bgLighter,
+                                        color: AppColors.accent,
+                                        minHeight: 3,
+                                      ),
+                                    ),
+                                    const SizedBox(width: 10),
+                                    SizedBox(
+                                      width: 130,
+                                      child: Text(
+                                          '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
+                                          style: const TextStyle(
+                                              color: AppColors.textGray,
+                                              fontSize: 11)),
+                                    ),
+                                    SizedBox(
+                                      width: 60,
+                                      child: Text(stLabel,
+                                          style: TextStyle(
+                                              color: stColor, fontSize: 11)),
+                                    ),
+                                  ],
+                                ),
+                              );
+                            },
+                          ),
                   ),
-                ),
-                const SizedBox(height: 10),
-                // 文件列表
-                Container(
-                  constraints: const BoxConstraints(maxHeight: 180),
-                  decoration: BoxDecoration(
-                    color: AppColors.bg,
-                    borderRadius: BorderRadius.circular(4),
-                  ),
-                  child: ListView.builder(
-                    shrinkWrap: true,
-                    itemCount: task.files.length,
-                    itemBuilder: (context, i) {
-                      final f = task.files[i];
-                      Color stColor = AppColors.textDim;
-                      String stLabel = '等待下载';
-                      switch (f.status) {
-                        case DownloadStatus.preparing:
-                          stColor = AppColors.yellow;
-                          stLabel = '正在准备';
-                        case DownloadStatus.downloading:
-                          stColor = AppColors.green;
-                          stLabel = '正在下载';
-                        case DownloadStatus.paused:
-                          stColor = AppColors.yellow;
-                          stLabel = '已暂停';
-                        case DownloadStatus.done:
-                          stColor = AppColors.green;
-                          stLabel = '已完成';
-                        case DownloadStatus.failed:
-                          stColor = AppColors.red;
-                          stLabel = '下载失败';
-                        default:
-                          stLabel = '等待下载';
-                      }
-                      return Padding(
-                        padding: const EdgeInsets.symmetric(
-                            horizontal: 12, vertical: 6),
-                        child: Row(
-                          children: [
-                            SizedBox(
-                              width: 200,
-                              child: Text(f.name,
-                                  maxLines: 1,
-                                  overflow: TextOverflow.ellipsis,
-                                  style: const TextStyle(
-                                      color: AppColors.textWhite,
-                                      fontSize: 12)),
-                            ),
-                            Expanded(
-                              child: LinearProgressIndicator(
-                                value: f.progress,
-                                backgroundColor: AppColors.bgLighter,
-                                color: AppColors.accent,
-                                minHeight: 3,
-                              ),
-                            ),
-                            const SizedBox(width: 10),
-                            SizedBox(
-                              width: 130,
-                              child: Text(
-                                  '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
-                                  style: const TextStyle(
-                                      color: AppColors.textGray,
-                                      fontSize: 11)),
-                            ),
-                            SizedBox(
-                              width: 60,
-                              child: Text(stLabel,
-                                  style: TextStyle(
-                                      color: stColor, fontSize: 11)),
-                            ),
-                          ],
-                        ),
-                      );
-                    },
-                  ),
-                ),
+                ],
                 const SizedBox(height: 18),
                 // 操作按钮
                 Row(
@@ -301,34 +437,54 @@
                                 }
                               },
                         style: ElevatedButton.styleFrom(
-                          backgroundColor: task.paused
-                              ? AppColors.accent
-                              : const Color(0xFF3A3F52),
+                          backgroundColor: AppColors.accent,
                           foregroundColor: Colors.white,
-                          disabledBackgroundColor:
-                              AppColors.green.withOpacity(0.3),
+                          disabledBackgroundColor: AppColors.bgLighter,
+                          disabledForegroundColor: AppColors.textDim,
                           padding: const EdgeInsets.symmetric(vertical: 12),
                         ),
-                        child: Text(task.finished
-                            ? '下载完成'
-                            : task.paused
-                                ? '继续下载'
-                                : '暂停下载'),
+                        child: Text(task.extracting
+                            ? '正在安装'
+                            : task.finished
+                                ? '下载完成'
+                                : task.paused
+                                    ? '继续下载'
+                                    : '暂停下载'),
                       ),
                     ),
                     const SizedBox(width: 12),
                     Expanded(
                       child: ElevatedButton(
-                        onPressed: () {
-                          DownloadManager.instance.cancelTask();
-                          Navigator.pop(context);
-                        },
+                        // 安装完成后变为启动按钮
+                        onPressed: task.extracting
+                            ? null
+                            : (task.finished && !task.extractFailed)
+                                ? () => _launchGame(task)
+                                : () {
+                                    DownloadManager.instance.cancelTask();
+                                    Navigator.pop(context);
+                                  },
                         style: ElevatedButton.styleFrom(
-                          backgroundColor: const Color(0xFF3A3F52),
+                          backgroundColor:
+                              (task.finished && !task.extractFailed)
+                                  ? AppColors.accent
+                                  : const Color(0xFF3A3F52),
                           foregroundColor: Colors.white,
+                          disabledBackgroundColor: AppColors.bgLighter,
+                          disabledForegroundColor: AppColors.textDim,
                           padding: const EdgeInsets.symmetric(vertical: 12),
                         ),
-                        child: const Text('取消安装'),
+                        child: (task.finished && !task.extractFailed)
+                            ? Row(
+                                mainAxisAlignment: MainAxisAlignment.center,
+                                children: [
+                                  const Icon(Icons.play_arrow, size: 18),
+                                  const SizedBox(width: 8),
+                                  Text(task.isTool ? '启动' : '启动游戏',
+                                      style: const TextStyle(fontSize: 14)),
+                                ],
+                              )
+                            : const Text('取消安装'),
                       ),
                     ),
                   ],
@@ -398,3 +554,215 @@
   }
   Process.run('explorer.exe', [p.normalize(dir.path)]);
 }
+
+/// 下载路径选择弹窗(详情页下载、资源库安装共用)
+/// [requiredGb] 游戏所需磁盘空间(GB),所选下载目录所在磁盘剩余空间不足时禁止下载
+class DownloadPathDialog extends StatefulWidget {
+  final String gameTitle;
+  final double requiredGb;
+  const DownloadPathDialog(
+      {super.key, required this.gameTitle, this.requiredGb = 0});
+  @override
+  State<DownloadPathDialog> createState() => _DownloadPathDialogState();
+}
+
+class _DownloadPathDialogState extends State<DownloadPathDialog> {
+  final _dlCtrl = TextEditingController();
+  final _insCtrl = TextEditingController();
+  double _freeBytes = -2; // -2 未检查,-1 无法获取
+  bool _checking = false;
+
+  /// 需要的空间(字节):优先"磁盘占用",未设置时回退"游戏大小"
+  double get _requiredBytes =>
+      widget.requiredGb > 0 ? widget.requiredGb * 1024 * 1024 * 1024 : 0;
+
+  bool get _insufficient =>
+      _requiredBytes > 0 && _freeBytes >= 0 && _freeBytes < _requiredBytes;
+
+  @override
+  void initState() {
+    super.initState();
+    _dlCtrl.addListener(_checkFreeSpace);
+    _load();
+  }
+
+  @override
+  void dispose() {
+    _dlCtrl.removeListener(_checkFreeSpace);
+    _dlCtrl.dispose();
+    _insCtrl.dispose();
+    super.dispose();
+  }
+
+  Future<void> _load() async {
+    final dl = await AppPrefs.getDownloadPath();
+    final ins = await AppPrefs.getInstallPath();
+    setState(() {
+      _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
+      _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
+    });
+    _checkFreeSpace();
+  }
+
+  /// 检查下载目录所在磁盘的剩余空间
+  void _checkFreeSpace() {
+    final path = _dlCtrl.text.trim();
+    if (path.isEmpty || _checking) return;
+    _checking = true;
+    getDiskFreeBytes(path).then((free) {
+      _checking = false;
+      if (!mounted) return;
+      // 检查期间路径又变了则重新检查
+      final cur = _dlCtrl.text.trim();
+      if (cur != path) {
+        _checkFreeSpace();
+        return;
+      }
+      setState(() => _freeBytes = free);
+    });
+  }
+
+  String get _freeInfo {
+    if (_checking) return '正在检查磁盘剩余空间...';
+    if (_freeBytes < 0) return '';
+    final freeGb = _freeBytes / 1024 / 1024 / 1024;
+    return '下载目录所在磁盘剩余空间:${freeGb.toStringAsFixed(1)} GB';
+  }
+
+  @override
+  Widget build(BuildContext context) {
+    return Dialog(
+      backgroundColor: const Color(0xFF1E2130),
+      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+      child: Container(
+        width: 500,
+        padding: const EdgeInsets.all(24),
+        child: Column(
+          mainAxisSize: MainAxisSize.min,
+          crossAxisAlignment: CrossAxisAlignment.start,
+          children: [
+            Row(
+              children: [
+                const Icon(Icons.folder,
+                    size: 16, color: AppColors.textGray),
+                const SizedBox(width: 8),
+                const Text('请选择下载安装路径',
+                    style: TextStyle(
+                        color: Colors.white,
+                        fontSize: 14,
+                        fontWeight: FontWeight.w500)),
+                const Spacer(),
+                GestureDetector(
+                  onTap: () => Navigator.pop(context, false),
+                  child: const Icon(Icons.close,
+                      size: 16, color: AppColors.textGray),
+                ),
+              ],
+            ),
+            const SizedBox(height: 18),
+            _pathRow('下载路径', _dlCtrl),
+            const SizedBox(height: 12),
+            _pathRow('安装路径', _insCtrl),
+            // 磁盘剩余空间提示
+            if (_requiredBytes > 0) ...[
+              const SizedBox(height: 10),
+              Text(
+                _insufficient
+                    ? '磁盘剩余空间不足(需要 ${widget.requiredGb.toStringAsFixed(1)} GB,'
+                      '当前剩余 ${(_freeBytes / 1024 / 1024 / 1024).toStringAsFixed(1)} GB),'
+                      '请选择其他磁盘!'
+                    : _freeInfo,
+                style: TextStyle(
+                    color: _insufficient
+                        ? AppColors.red
+                        : AppColors.textGray,
+                    fontSize: 12),
+              ),
+            ],
+            const SizedBox(height: 20),
+            Row(
+              mainAxisAlignment: MainAxisAlignment.end,
+              children: [
+                OutlinedButton(
+                  onPressed: () => Navigator.pop(context, false),
+                  style: OutlinedButton.styleFrom(
+                    foregroundColor: AppColors.textGray,
+                    side: const BorderSide(color: AppColors.bgLighter),
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('取消'),
+                ),
+                const SizedBox(width: 12),
+                ElevatedButton(
+                  // 磁盘空间不足时禁止下载
+                  onPressed: (_checking || _insufficient)
+                      ? null
+                      : () async {
+                          await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
+                          if (context.mounted) {
+                            Navigator.pop(context, true);
+                          }
+                        },
+                  style: ElevatedButton.styleFrom(
+                    backgroundColor: AppColors.accent,
+                    disabledBackgroundColor: AppColors.bgLighter,
+                    disabledForegroundColor: AppColors.textDim,
+                    foregroundColor: Colors.white,
+                    padding: const EdgeInsets.symmetric(
+                        horizontal: 22, vertical: 10),
+                  ),
+                  child: const Text('确认'),
+                ),
+              ],
+            ),
+          ],
+        ),
+      ),
+    );
+  }
+
+  Widget _pathRow(String label, TextEditingController ctrl) {
+    return Column(
+      crossAxisAlignment: CrossAxisAlignment.start,
+      children: [
+        Text(label,
+            style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
+        const SizedBox(height: 6),
+        Row(
+          children: [
+            Expanded(
+              child: TextField(
+                controller: ctrl,
+                style: const TextStyle(color: Colors.black, fontSize: 13),
+                decoration: InputDecoration(
+                  filled: true,
+                  fillColor: Colors.white,
+                  contentPadding: const EdgeInsets.symmetric(
+                      horizontal: 10, vertical: 10),
+                  border: OutlineInputBorder(
+                      borderRadius: BorderRadius.circular(4),
+                      borderSide: BorderSide.none),
+                ),
+              ),
+            ),
+            const SizedBox(width: 8),
+            ElevatedButton(
+              onPressed: () async {
+                final dir = await FilePicker.platform.getDirectoryPath();
+                if (dir != null) setState(() => ctrl.text = dir);
+              },
+              style: ElevatedButton.styleFrom(
+                backgroundColor: AppColors.accent,
+                foregroundColor: Colors.white,
+                padding: const EdgeInsets.symmetric(
+                    horizontal: 14, vertical: 11),
+              ),
+              child: const Text('选择目录', style: TextStyle(fontSize: 12)),
+            ),
+          ],
+        ),
+      ],
+    );
+  }
+}

--
Gitblit v1.10.0