Files
EasyDesignCollection/lib/ui/update_dialog.dart
T
admin 0ce50d4b8d feat(update): 应用内更新(检查/下载/安装)与发版流程;版本 1.2.0
- 工具栏新增检查更新按钮:启动静默检查,发现新版本时显示红色角标;
  未检测到新版本或安装包时弹窗提示「当前已是最新版本」
- 更新源:Gitea Releases(说明 = Release 正文 Markdown;安装包 = 附件,
  不进入 git 历史,仓库保持精简)
- 安卓:下载 APK → FileProvider + 系统安装器直接覆盖安装(签名一致)
- Windows:下载绿色版 zip → 解压 → 生成替换脚本,主程序退出后原地覆盖并自动重启
- 新增 lib/update/update_service.dart、lib/ui/update_dialog.dart、lib/version.dart
- 安卓侧:REQUEST_INSTALL_PACKAGES + FileProvider + installApk/getCacheDir 通道 + androidx.core
- 发版工具:scripts/publish_release.ps1(打包 dist、创建 Release、上传附件)
- 测试:test/update_version_test.dart(版本比较 4 组);启动检查在测试环境自动跳过
- 版本号 1.2.0+12;BUILD-NOTES 补充应用内更新与发版流程
2026-10-08 21:08:18 +08:00

320 lines
12 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// 应用内更新对话框。
///
/// 展示新版本号、更新说明(Release 正文即为 Markdown 文本)与安装包信息;
/// 底部提供「立即更新」按钮与下载进度条:
/// - Android:下载 APK 到应用缓存目录,经 FileProvider 交给系统安装程序;
/// - Windows:下载绿色版整包(zip),解压后生成替换脚本——等待本程序退出、
/// 原地覆盖 dist 目录并自动重启,无需安装。
library;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state/app_controller.dart';
import '../theme/tokens.dart';
import '../update/update_service.dart';
import '../version.dart';
import 'dialogs.dart';
/// 应用内更新对话框。
class UpdateDialog extends StatefulWidget {
/// 构造;[info] 为本次检测到的更新信息。
const UpdateDialog({super.key, required this.controller, required this.info});
/// 全局应用控制器(用于状态栏提示)。
final AppController controller;
/// 更新信息。
final UpdateInfo info;
@override
State<UpdateDialog> createState() => _UpdateDialogState();
}
class _UpdateDialogState extends State<UpdateDialog> {
/// 与安卓原生桥接(复用现有 `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<void> _start() async {
setState(() {
_busy = true;
_error = null;
_cancelled = false;
_done = false;
_progress = -1;
_received = 0;
_status = '正在下载更新包…';
});
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;
}
if (mounted) setState(() => _busy = false);
}
/// 安卓:下载 APK → 交给系统安装程序。
Future<void> _updateAndroid() async {
final String? dir = await _channel.invokeMethod<String>('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<bool>('installApk', <String, dynamic>{'path': dest});
if (mounted) {
setState(() {
_status = '已交给系统安装程序,请在弹出的界面完成安装。';
_done = true;
});
}
}
/// Windows:下载绿色版整包 → 解压 → 生成替换脚本 → 退出并自动重启。
Future<void> _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', <String>['-xf', zipPath, '-C', extractDir]);
if (r.exitCode != 0) throw Exception('解压失败:${r.stderr}');
// 兼容两种打包方式:zip 根目录即程序文件,或多包一层 dist/。
String srcDir = extractDir;
if (!File('$extractDir\\sequence_diagram.exe').existsSync()) {
if (File('$extractDir\\dist\\sequence_diagram.exe').existsSync()) {
srcDir = '$extractDir\\dist';
} else {
throw Exception('更新包内容不完整(未找到 sequence_diagram.exe)');
}
}
if (mounted) setState(() => _status = '正在准备覆盖更新…');
final String appDir = File(Platform.resolvedExecutable).parent.path;
final String batPath = '${tmp.path}\\apply_update.bat';
// 生成替换脚本:等待本程序退出 → 原地覆盖 → 重新启动。
// 内容保持纯 ASCII,源/目标路径通过参数传入(cmd 以 UTF-16 接收参数,
// 中文安装路径也能正确处理);脚本文件本身不包含路径,避免编码问题。
File(batPath).writeAsStringSync(
'@echo off\r\n'
':wait\r\n'
'tasklist /fi "IMAGENAME eq sequence_diagram.exe" | find /i "sequence_diagram.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'
'start "" "%~2\\sequence_diagram.exe"\r\n'
'del "%~f0"\r\n',
flush: true,
);
await Process.start(
'cmd',
<String>['/c', batPath, srcDir, appDir],
mode: ProcessStartMode.detached,
);
if (mounted) {
setState(() {
_status = '更新就绪,软件即将重启完成覆盖…';
_done = true;
});
}
await Future<void>.delayed(const Duration(milliseconds: 900));
exit(0);
}
/// 下载进度回调:刷新进度条与状态文本。
void _onProgress(double progress, int received) {
if (!mounted) return;
setState(() {
_progress = progress;
_received = received;
});
}
/// 取消 / 关闭按钮:下载中先中断下载。
void _cancel() {
_cancelled = true;
}
@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 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: <Widget>[
// 标题
Row(
children: <Widget>[
Icon(Icons.system_update_alt, 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(
'安装包:${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) ...<Widget>[
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: <Widget>[
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',
style: TextStyle(color: t.dim, fontSize: 11)),
],
),
],
if (_error != null) ...<Widget>[
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)),
),
],
const SizedBox(height: 14),
// 操作按钮
Row(
children: <Widget>[
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),
),
),
],
),
],
),
),
),
);
}
}