/// 应用内更新对话框。 /// /// 展示新版本号、更新说明(Release 正文即为 Markdown 文本)与安装包信息; /// 底部提供「立即更新」按钮与下载进度条: /// - Android:下载 APK 到应用缓存目录,经 FileProvider 交给系统安装程序; /// - Windows:下载绿色版整包(zip),解压后生成替换脚本——等待本程序退出、 /// 原地覆盖 dist 目录并自动重启,无需安装。 library; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:sequence_diagram/state/app_controller.dart'; import 'package:sequence_diagram/theme/tokens.dart'; import 'package:sequence_diagram/update/keep_awake.dart'; import 'package:sequence_diagram/update/update_service.dart'; import 'package:sequence_diagram/version.dart'; import 'dialogs.dart'; import 'update_icon.dart'; /// 应用内更新对话框。 class UpdateDialog extends StatefulWidget { /// 构造;[info] 为本次检测到的更新信息。 const UpdateDialog({super.key, required this.controller, required this.info}); /// 全局应用控制器(用于状态栏提示)。 final AppController controller; /// 更新信息。 final UpdateInfo info; @override State createState() => _UpdateDialogState(); } class _UpdateDialogState extends State { /// 与安卓原生桥接(复用现有 `seqstudio/docs` 通道)。 static const MethodChannel _channel = MethodChannel('seqstudio/docs'); bool _busy = false; bool _cancelled = false; bool _done = false; double _progress = -1; int _received = 0; String _status = ''; String? _error; /// 「立即更新」:按平台执行下载与安装 / 覆盖更新。 Future _start() async { setState(() { _busy = true; _error = null; _cancelled = false; _done = false; _progress = -1; _received = 0; _status = '正在下载更新包…'; }); // 下载期间保持屏幕常亮:避免锁屏中断下载(Android / Windows)。 await KeepAwake.enable(); try { if (Platform.isAndroid) { await _updateAndroid(); } else if (Platform.isWindows) { await _updateWindows(); } else { throw Exception('当前平台暂不支持应用内更新'); } } catch (e) { if (mounted) { setState(() { _error = '$e'; _busy = false; }); } return; } finally { await KeepAwake.disable(); } if (mounted) setState(() => _busy = false); } /// 安卓:下载 APK → 交给系统安装程序。 Future _updateAndroid() async { final String? dir = await _channel.invokeMethod('getCacheDir'); if (dir == null || dir.isEmpty) throw Exception('无法获取应用缓存目录'); final String dest = '$dir${Platform.pathSeparator}${widget.info.assetName}'; await UpdateService.download( url: widget.info.assetUrl, destPath: dest, isCancelled: () => _cancelled, onProgress: _onProgress, ); if (_cancelled) throw Exception('已取消'); if (mounted) setState(() => _status = '正在启动系统安装程序…'); await _channel.invokeMethod('installApk', {'path': dest}); if (mounted) { setState(() { _status = '已交给系统安装程序,请在弹出的界面完成安装。'; _done = true; }); } } /// Windows:下载绿色版整包 → 解压 → 生成替换脚本 → 退出并自动重启。 Future _updateWindows() async { final Directory tmp = await Directory.systemTemp.createTemp('seq_update_'); final String zipPath = '${tmp.path}\\update.zip'; await UpdateService.download( url: widget.info.assetUrl, destPath: zipPath, isCancelled: () => _cancelled, onProgress: _onProgress, ); if (_cancelled) throw Exception('已取消'); if (mounted) setState(() => _status = '正在解压更新包…'); final String extractDir = '${tmp.path}\\app'; await Directory(extractDir).create(recursive: true); final ProcessResult r = await Process.run('tar', ['-xf', zipPath, '-C', extractDir]); if (r.exitCode != 0) throw Exception('解压失败:${r.stderr}'); // 兼容两种打包方式:zip 根目录即程序文件,或多包一层 dist/。 // 同时识别新版 ProcessDesignSuite.exe 与旧版 EasyDesignCollection.exe。 const List exeNames = [ 'ProcessDesignSuite.exe', 'EasyDesignCollection.exe', ]; String? srcDir; String? exeName; for (final String base in [extractDir, '$extractDir\\dist']) { for (final String name in exeNames) { if (File('$base\\$name').existsSync()) { srcDir = base; exeName = name; break; } } if (srcDir != null) break; } if (srcDir == null || exeName == null) { throw Exception('更新包内容不完整(未找到 ProcessDesignSuite.exe)'); } if (mounted) setState(() => _status = '正在准备覆盖更新…'); final String appDir = File(Platform.resolvedExecutable).parent.path; final String batPath = '${tmp.path}\\apply_update.bat'; // 升级过渡期可能残留旧版 exe:换成新名字时顺手清理旧文件。 final String cleanup = exeName == 'ProcessDesignSuite.exe' ? 'if exist "%~2\\EasyDesignCollection.exe" del /q "%~2\\EasyDesignCollection.exe"\r\n' 'if exist "%~2\\EasyDesignCollection.exe.manifest" del /q "%~2\\EasyDesignCollection.exe.manifest"\r\n' : ''; // 生成替换脚本:等待本程序退出 → 原地覆盖 → 重新启动。 // 内容保持纯 ASCII,源/目标路径通过参数传入(cmd 以 UTF-16 接收参数, // 中文安装路径也能正确处理);脚本文件本身不包含路径,避免编码问题。 File(batPath).writeAsStringSync( '@echo off\r\n' ':wait\r\n' 'tasklist /fi "IMAGENAME eq ProcessDesignSuite.exe" | find /i "ProcessDesignSuite.exe" >nul\r\n' 'if not errorlevel 1 (\r\n' ' ping -n 1 -w 600 127.0.0.1 >nul\r\n' ' goto wait\r\n' ')\r\n' 'tasklist /fi "IMAGENAME eq EasyDesignCollection.exe" | find /i "EasyDesignCollection.exe" >nul\r\n' 'if not errorlevel 1 (\r\n' ' ping -n 1 -w 600 127.0.0.1 >nul\r\n' ' goto wait\r\n' ')\r\n' 'xcopy /e /i /y /q "%~1\\*" "%~2\\"\r\n' '$cleanup' 'start "" "%~2\\$exeName"\r\n' 'del "%~f0"\r\n', flush: true, ); await Process.start( 'cmd', ['/c', batPath, srcDir, appDir], mode: ProcessStartMode.detached, ); if (mounted) { setState(() { _status = '更新就绪,软件即将重启完成覆盖…'; _done = true; }); } await Future.delayed(const Duration(milliseconds: 900)); await KeepAwake.forceOff(); exit(0); } /// 下载进度回调:刷新进度条与状态文本。 void _onProgress(double progress, int received) { if (!mounted) return; setState(() { _progress = progress; _received = received; }); } /// 取消 / 关闭按钮:下载中先中断下载。 void _cancel() { _cancelled = true; } @override void dispose() { // 兜底:对话框销毁后不再强制常亮。 KeepAwake.forceOff(); super.dispose(); } @override Widget build(BuildContext context) { final Tokens t = context.tok; final UpdateInfo info = widget.info; final String sizeText = info.assetSize > 0 ? '${(info.assetSize / 1048576).toStringAsFixed(1)} MB' : ''; return PopScope( // 下载中禁止返回键退出;未下载时可返回键关闭。 // 点击对话框外的灰色区域始终无响应(barrierDismissible: false)。 canPop: !_busy, child: Dialog( backgroundColor: t.dialog, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)), child: scaledDialogBox( context, 620, 560, Padding( padding: const EdgeInsets.all(18), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 标题 Row( children: [ UpdateIcon(size: 21, color: t.accent), const SizedBox(width: 8), Text('发现新版本 v${info.version}', style: TextStyle(color: t.text, fontSize: 17, fontWeight: FontWeight.w700)), const Spacer(), Text('当前 v$kAppVersion', style: TextStyle(color: t.dim, fontSize: 11.5)), ], ), const SizedBox(height: 4), Text( '将直接升级到最新版本 v${info.version}(无需逐版本安装)', style: TextStyle(color: t.accent, fontSize: 11), ), const SizedBox(height: 2), Text( '安装包:${info.assetName}${sizeText.isEmpty ? '' : '($sizeText)'}', style: TextStyle(color: t.dim, fontSize: 11), maxLines: 1, overflow: TextOverflow.ellipsis, ), const Divider(height: 20), // 更新说明(Release 正文) Text('更新内容', style: TextStyle(color: t.sub, fontSize: 12.5, fontWeight: FontWeight.w600)), const SizedBox(height: 6), Expanded( child: Container( width: double.infinity, padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: t.panel2, borderRadius: BorderRadius.circular(10), border: Border.all(color: t.line2), ), child: SingleChildScrollView( child: SelectableText( info.notes.trim().isEmpty ? '(本次更新未提供说明)' : info.notes, style: TextStyle(color: t.text, fontSize: 12.5, height: 1.7), ), ), ), ), // 进度 / 状态 / 错误 if (_busy || _done) ...[ const SizedBox(height: 12), ClipRRect( borderRadius: BorderRadius.circular(3), child: LinearProgressIndicator( value: _done ? 1 : (_progress >= 0 ? _progress : null), minHeight: 5, color: t.accent2, backgroundColor: t.line2, ), ), const SizedBox(height: 6), Row( children: [ Expanded( child: Text(_status, style: TextStyle(color: t.sub, fontSize: 12)), ), if (_busy && _progress >= 0) Text('${(_progress * 100).clamp(0, 100).toStringAsFixed(0)}% · ' '${(_received / 1048576).toStringAsFixed(1)} MB · 限速 320KB/s', style: TextStyle(color: t.dim, fontSize: 11)), ], ), ], if (_error != null) ...[ const SizedBox(height: 10), Container( width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: _error == '已取消' ? t.panel2 : t.danger.withValues(alpha: 0.12), borderRadius: BorderRadius.circular(8), border: Border.all( color: _error == '已取消' ? t.line2 : t.danger.withValues(alpha: 0.5)), ), child: Text(_error!, style: TextStyle( color: _error == '已取消' ? t.sub : t.danger, fontSize: 12, height: 1.5)), ), ], // 下载提示:明确提醒保持屏幕常亮与网络连接,避免下载中断。 Container( width: double.infinity, padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: t.warn.withValues(alpha: 0.10), borderRadius: BorderRadius.circular(8), border: Border.all(color: t.warn.withValues(alpha: 0.35)), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Icon(Icons.lightbulb_outline, size: 15, color: t.warn), const SizedBox(width: 8), Expanded( child: Text( '更新过程中软件会自动保持屏幕常亮;请保持界面打开、网络连接稳定,' '不要退出软件,避免更新包下载中断。', style: TextStyle(color: t.warn, fontSize: 11.5, height: 1.5), ), ), ], ), ), const SizedBox(height: 14), // 操作按钮 Row( children: [ Expanded( child: Text( Platform.isAndroid ? '下载后由系统安装程序完成安装(签名一致可直接覆盖)' : '绿色版原地覆盖,软件会自动重启', style: TextStyle(color: t.dim, fontSize: 11), ), ), TextButton( onPressed: () { if (_busy) _cancel(); Navigator.pop(context); }, child: Text(_busy ? '取消下载' : '关闭'), ), const SizedBox(width: 8), FilledButton.icon( onPressed: _busy || _done ? null : _start, icon: const Icon(Icons.download, size: 16), label: Text(_done ? '已完成' : '立即更新'), style: FilledButton.styleFrom( backgroundColor: t.accent2, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(9)), padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12), ), ), ], ), ], ), ), ), ), ); } }