feat: 导出固定 1920×1080(标题恒定左上、内容自适应缩放)+ 安卓保存位置可配置

- 导出重设计(exe 与安卓一致):SVG/PNG 固定 1920×1080;标题恒定左上、图例恒定左下;内容按包围盒等比缩放居中(export_fit.dart 统一计算,不裁切不溢出);PNG 改为离屏 1920×1080 渲染

- 安卓保存位置可改:保存/打开对话框新增「更改位置」,基础目录可选文档/下载/图片 + 自定义子文件夹,设置持久化(save_location.json)

- 原生通道 seqstudio/docs 支持 base/folder 参数;新增 export_test.dart 回归(尺寸/标题/transform)

- 重建 dist(Windows)与签名 APK
This commit is contained in:
admin
2026-10-07 09:27:45 +08:00
parent 50d2303951
commit c1d9f27952
10 changed files with 533 additions and 120 deletions
+81
View File
@@ -0,0 +1,81 @@
/// 导出适配:固定 1920×1080 画布下,把时序图内容缩放到内容区并居中,
/// 供 PNG 渲染器与 SVG 写入器共用,保证两种导出几何完全一致。
///
/// 约定:
/// - 画布固定 1920×1080;
/// - 标题固定在左上角(标题区 0–128px);
/// - 内容区 = (48, 128) → (1872, 1016),图例固定左下角;
/// - 内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
library;
import 'dart:math' as math;
import 'package:flutter/material.dart' hide Action;
import '../layout/layout.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../render/bar_painter.dart';
/// 导出画布尺寸(固定)。
const Size kExportSize = Size(1920, 1080);
/// 内容区(标题下方、图例上方)。
const Rect kExportContentArea = Rect.fromLTRB(48, 128, 1872, 1016);
/// 导出适配结果:内容变换 `scale` + `translate(tx, ty)`。
class ExportFit {
/// 构造适配结果。
const ExportFit(this.scale, this.tx, this.ty);
/// 缩放系数。
final double scale;
/// 水平平移。
final double tx;
/// 垂直平移。
final double ty;
/// SVG transform 属性值。
String get svgTransform =>
'translate(${tx.toStringAsFixed(1)} ${ty.toStringAsFixed(1)}) scale(${scale.toStringAsFixed(4)})';
}
/// 计算内容在 [area] 内的适配变换。
///
/// 先以 1920×1080 为参考画布求内容包围盒,再等比缩放并居中。
ExportFit computeExportFit(Project project, ViewMode mode, Rect area) {
Rect bounds;
if (mode == ViewMode.bar) {
final BarLayout l = BarLayout(project, kExportSize);
final int n = l.lanes.length;
final double bottom = n == 0 ? BarLayout.topPad + BarLayout.rowVisual : l.yFor(n) + BarLayout.rowVisual + 8;
bounds = Rect.fromLTRB(12, BarPainter.phaseBandTop - 14, l.plotRight + 120, bottom);
} else {
final CircularLayout l = CircularLayout(project, kExportSize);
final double rExt = l.tickR + 100;
bounds = Rect.fromLTRB(l.center.dx - rExt, l.center.dy - rExt, l.center.dx + rExt, l.center.dy + rExt);
}
if (bounds.width <= 1 || bounds.height <= 1) {
return const ExportFit(1, 0, 0);
}
final double s = math.min(area.width / bounds.width, area.height / bounds.height).clamp(0.2, 1.6);
final double tx = area.left + (area.width - bounds.width * s) / 2 - bounds.left * s;
final double ty = area.top + (area.height - bounds.height * s) / 2 - bounds.top * s;
return ExportFit(s, tx, ty);
}
/// 导出标题(与画布浮层一致)。
String exportTitle(ViewMode mode) =>
mode == ViewMode.bar ? '条形时序视图' : '圆周时序视图';
/// 导出副标题(与画布浮层一致)。
String exportSubtitle(Project project, ViewMode mode) {
if (mode == ViewMode.bar) {
return '箭头表示动作之间关联(绿色实线 FS 严格顺序 / 琥珀虚线 SS 并行重叠)';
}
return '同心圆环 = 动作层 · 1 圈 = 1 循环 = ${tfmt(project.cycle.durationMs, project.units)} = 360° = 100%';
}
/// 导出图例(左下角固定)。
String exportLegend(Project project) =>
'时序图设计器 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°';
+97
View File
@@ -0,0 +1,97 @@
/// PNG 导出渲染器:把时序图渲染为固定 1920×1080 的位图。
///
/// 与 SVG 导出共用同一套适配计算([computeExportFit]),保证两种格式几何一致:
/// - 背景铺满 1920×1080;
/// - 标题固定在左上角、图例固定在左下角;
/// - 内容(条形 / 圆周)按自身包围盒等比缩放并居中到内容区。
library;
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart' hide Action;
import '../model/models.dart';
import '../render/bar_painter.dart';
import '../render/circular_painter.dart';
import '../theme/tokens.dart';
import 'export_fit.dart';
/// 渲染导出 PNG 并返回字节。
///
/// 参数:
/// - [project]:数据源;
/// - [tokens]:配色令牌;
/// - [criticalActions]/[criticalDeps]:关键路径高亮(与屏幕一致)。
Future<Uint8List> renderExportPng({
required Project project,
required Tokens tokens,
required Set<String> criticalActions,
required Set<String> criticalDeps,
}) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final double w = kExportSize.width;
final double h = kExportSize.height;
// 背景铺满。
canvas.drawRect(Rect.fromLTWH(0, 0, w, h), Paint()..color = tokens.bg);
// 标题:固定左上角。
final ViewMode mode = project.viewState.mode;
_text(canvas, exportTitle(mode), const Offset(48, 36),
color: tokens.text, size: 34, weight: FontWeight.w700);
_text(canvas, exportSubtitle(project, mode), const Offset(48, 88),
color: tokens.sub, size: 16, weight: FontWeight.w400);
// 内容:适配缩放并居中到内容区。
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
canvas.save();
canvas.translate(fit.tx, fit.ty);
canvas.scale(fit.scale);
if (mode == ViewMode.bar) {
BarPainter(
project: project,
tokens: tokens,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
} else {
CircularPainter(
project: project,
tokens: tokens,
criticalActions: criticalActions,
criticalDeps: criticalDeps,
selectedIds: const <String>{},
).paint(canvas, kExportSize);
}
canvas.restore();
// 图例:固定左下角。
_text(canvas, exportLegend(project), Offset(48, h - 38),
color: tokens.sub, size: 15, weight: FontWeight.w400);
final ui.Image image = await recorder.endRecording().toImage(w.toInt(), h.toInt());
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
return data!.buffer.asUint8List();
}
/// 用统一字体绘制单行文本。
void _text(Canvas canvas, String s, Offset at,
{required Color color, required double size, required FontWeight weight}) {
final TextPainter tp = TextPainter(
text: TextSpan(
text: s,
style: TextStyle(
color: color,
fontSize: size,
fontWeight: weight,
fontFamily: 'Microsoft YaHei UI',
fontFamilyFallback: const <String>['Microsoft YaHei', 'Noto Sans SC', 'sans-serif'],
),
),
textDirection: ui.TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
}
+28 -21
View File
@@ -10,8 +10,10 @@
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
///
/// 输出约定:
/// - 画布固定 2560×1440,通过 `viewBox` 支持无损缩放。
/// 输出约定(与 PNG 导出一致):
/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
library;
@@ -22,6 +24,7 @@ import '../layout/layout.dart';
import '../model/models.dart';
import '../model/units.dart';
import '../theme/tokens.dart';
import 'export_fit.dart';
/// SVG 文档写入器。
///
@@ -51,28 +54,42 @@ class SvgWriter {
/// 生成完整 SVG 文档字符串。
///
/// 输出约定(与 PNG 导出一致):
/// - 画布固定 1920×1080;
/// - 标题固定在左上角、图例固定在左下角;
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
///
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
String build() {
// 固定逻辑画布尺寸;viewBox 与 width/height 相同,缩放时几何不失真。
final double w = 2560;
final double h = 1440;
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="$w" height="$h" viewBox="0 0 $w $h">');
const double w = 1920;
const double h = 1080;
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">');
// 先写箭头 marker 定义,供后续依赖路径引用。
_defs();
// 背景层:铺满整张画布。
_b.write('<g id="background">');
_rect(0, 0, w, h, fill: _hex(tokens.bg));
_b.write('</g>');
// 按当前视图模式生成主体内容。
// 标题:固定左上角。
_b.write('<g id="title">');
_text(48, 60, exportTitle(mode), color: _hex(tokens.text), size: 34, weight: '700');
_text(48, 104, exportSubtitle(project, mode), color: _hex(tokens.sub), size: 16);
_b.write('</g>');
// 内容:适配缩放并居中到内容区。
final ExportFit fit = computeExportFit(project, mode, kExportContentArea);
_b.write('<g id="content" transform="${fit.svgTransform}">');
if (mode == ViewMode.bar) {
_barView(Size(w, h));
_barView(const Size(w, h));
} else {
_circularView(Size(w, h));
_circularView(const Size(w, h));
}
// 图例始终绘制在最上层。
_legend(w, h);
_b.write('</g>');
// 图例:固定左下角。
_b.write('<g id="legend">');
_text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15);
_b.write('</g>');
_b.write('</svg>');
return _b.toString();
}
@@ -253,16 +270,6 @@ class SvgWriter {
}
}
/// 写入图例分组,展示工程名、循环时长与 360° 的等价关系。
///
/// 参数 [w]/[h] 为画布宽高,用于定位到左下角。
void _legend(double w, double h) {
_b.write('<g id="legend">');
_text(24, h - 28, '时序图设计器 · ${project.name} · 循环 ${tfmt(project.cycle.durationMs, project.units)} = 360°',
color: _hex(tokens.sub), size: 13);
_b.write('</g>');
}
/// 生成一段圆弧的 SVG `d` 路径字符串。
///
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
+74 -10
View File
@@ -1,17 +1,23 @@
/// 安卓公共 Documents(Documents/SequenceDiagram)读写服务。
/// 安卓公共存储读写服务。
///
/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现:
/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规);
/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。
///
/// 保存位置可配置:基础目录(Documents / Download / Pictures)+ 子文件夹名,
/// 设置保存在应用私有目录的 `save_location.json`,跨会话生效。
///
/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。
library;
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
/// 安卓公共文档读写。
import 'storage.dart';
/// 安卓公共存储读写。
class AndroidDocs {
AndroidDocs._();
@@ -21,34 +27,92 @@ class AndroidDocs {
/// 是否可用(仅 Android)。
static bool get isAvailable => Platform.isAndroid;
/// 用于展示的目录描述。
static const String displayDir = 'Documents/SequenceDiagram';
/// 可选的基础目录:文档 / 下载 / 图片。
static const List<String> baseOptions = <String>['documents', 'downloads', 'pictures'];
/// 保存文件到公共 Documents/SequenceDiagram,返回展示位置。
///
/// 参数 [name] 文件名(含后缀);[data] 文件内容;[mime] 可选 MIME 类型。
/// 基础目录的展示名。
static String baseLabel(String base) => switch (base) {
'downloads' => 'Download',
'pictures' => 'Pictures',
_ => 'Documents',
};
/// 当前配置(懒加载一次)。
static Map<String, String> _settings = <String, String>{};
/// 设置文件(应用私有目录,不对外可见)。
static File get _settingsFile => File(
'${Storage.instance.appDir.path}${Platform.pathSeparator}save_location.json');
/// 读取当前保存位置配置。
static Map<String, String> settings() {
if (_settings.isNotEmpty) return _settings;
try {
if (_settingsFile.existsSync()) {
final Map<String, dynamic> j = jsonDecode(_settingsFile.readAsStringSync()) as Map<String, dynamic>;
_settings = <String, String>{
'base': j['base'] as String? ?? 'documents',
'folder': j['folder'] as String? ?? 'SequenceDiagram',
};
}
} catch (_) {}
if (_settings.isEmpty) {
_settings = <String, String>{'base': 'documents', 'folder': 'SequenceDiagram'};
}
return _settings;
}
/// 写入保存位置配置并立即生效。
static Future<void> saveSettings(String base, String folder) async {
_settings = <String, String>{
'base': baseOptions.contains(base) ? base : 'documents',
'folder': folder.trim().isEmpty ? 'SequenceDiagram' : folder.trim(),
};
try {
await _settingsFile.parent.create(recursive: true);
await _settingsFile.writeAsString(jsonEncode(_settings), flush: true);
} catch (_) {}
}
/// 当前保存位置的展示描述(如 `Documents/SequenceDiagram`)。
static String location() {
final Map<String, String> s = settings();
return '${baseLabel(s['base'] ?? 'documents')}/${s['folder'] ?? 'SequenceDiagram'}';
}
/// 保存文件到配置的公共目录,返回展示位置。
static Future<String> saveFile(String name, Uint8List data, {String? mime}) async {
final Map<String, String> s = settings();
final Object? r = await _channel.invokeMethod<Object?>('saveFile', <String, Object?>{
'name': name,
'data': data,
'mime': mime,
'base': s['base'],
'folder': s['folder'],
});
return r as String;
}
/// 列出 Documents/SequenceDiagram 下的文件(`[{name, size}]`,新在前)。
/// 列出配置目录下的文件(`[{name, size}]`,新在前)。
static Future<List<Map<String, dynamic>>> listFiles() async {
final Object? r = await _channel.invokeMethod<Object?>('listFiles');
final Map<String, String> s = settings();
final Object? r = await _channel.invokeMethod<Object?>('listFiles', <String, Object?>{
'base': s['base'],
'folder': s['folder'],
});
final List<Object?> list = (r as List<Object?>?) ?? const <Object?>[];
return list
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
.toList();
}
/// 读取 Documents/SequenceDiagram 下的文件内容;不存在返回 null。
/// 读取配置目录下的文件内容;不存在返回 null。
static Future<Uint8List?> readFile(String name) async {
final Map<String, String> s = settings();
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
'name': name,
'base': s['base'],
'folder': s['folder'],
});
if (r == null) return null;
return r as Uint8List;
+25 -47
View File
@@ -11,12 +11,11 @@
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/material.dart' hide Action;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../export/export_renderer.dart';
import '../export/svg_writer.dart';
import '../model/models.dart';
import '../model/units.dart';
@@ -45,9 +44,6 @@ class AppShell extends StatefulWidget {
/// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态,
/// 并提供文件操作、导出与快捷键处理。
class _AppShellState extends State<AppShell> {
/// 画布舞台的绘制边界 key,用于 PNG 导出时抓取像素。
final GlobalKey _stageKey = GlobalKey();
// ---- 侧栏状态机:可见(visible) × 钉住(pinned) × 悬停(hover) ----
/// 左侧栏是否可见。
bool _leftVisible = true;
@@ -170,7 +166,7 @@ class _AppShellState extends State<AppShell> {
return;
}
c.loadProject(Project.decode(utf8.decode(bytes)), path: null);
c.setStatus('已打开 ${AndroidDocs.displayDir}/$name');
c.setStatus('已打开 ${AndroidDocs.location()}/$name');
} catch (e) {
if (mounted) await showMessage(context, '打开失败', '$e');
}
@@ -212,7 +208,7 @@ class _AppShellState extends State<AppShell> {
try {
final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode()));
await AndroidDocs.saveFile(name, data, mime: 'application/json');
await c.markSaved('${AndroidDocs.displayDir}/$name');
await c.markSaved('${AndroidDocs.location()}/$name');
} catch (e) {
if (mounted) await showMessage(context, '保存失败', '$e');
}
@@ -258,7 +254,7 @@ class _AppShellState extends State<AppShell> {
mode: c.project.viewState.mode,
).build();
await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml');
if (mounted) c.setStatus('已导出 ${AndroidDocs.displayDir}/$name');
if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
} catch (e) {
if (mounted) await showMessage(context, '导出失败', '$e');
}
@@ -284,14 +280,26 @@ class _AppShellState extends State<AppShell> {
}
}
/// 导出 PNG:把画布舞台的 [RenderRepaintBoundary] 以 2 倍像素比
/// 渲染为位图并写入文件。
/// 导出 PNG:以固定 1920×1080 画布离屏渲染(标题固定左上、内容自适应缩放)。
Future<void> _exportPng() async {
if (!c.licensed) {
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
return;
}
// 安卓版:写入公共 Documents/SequenceDiagram。
final Uint8List bytes;
try {
bytes = await renderExportPng(
project: c.project,
tokens: Tokens.of(c.brightness),
criticalActions: c.criticalActions,
criticalDeps: c.criticalDeps,
);
} catch (e) {
if (mounted) await showMessage(context, '导出失败', '$e');
return;
}
if (!mounted) return;
// 安卓版:写入配置的公共目录。
if (AndroidDocs.isAvailable) {
final String? name = await showDialog<String>(
context: context,
@@ -303,13 +311,8 @@ class _AppShellState extends State<AppShell> {
);
if (name == null) return;
try {
// 抓取画布舞台的渲染对象并转换为图像。
final RenderRepaintBoundary boundary =
_stageKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage(pixelRatio: 2);
final ByteData? bd = await image.toByteData(format: ui.ImageByteFormat.png);
await AndroidDocs.saveFile(name, bd!.buffer.asUint8List(), mime: 'image/png');
if (mounted) c.setStatus('已导出 ${AndroidDocs.displayDir}/$name');
await AndroidDocs.saveFile(name, bytes, mime: 'image/png');
if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
} catch (e) {
if (mounted) await showMessage(context, '导出失败', '$e');
}
@@ -323,12 +326,7 @@ class _AppShellState extends State<AppShell> {
);
if (path == null) return;
try {
// 抓取画布舞台的渲染对象并转换为图像。
final RenderRepaintBoundary boundary =
_stageKey.currentContext!.findRenderObject()! as RenderRepaintBoundary;
final ui.Image image = await boundary.toImage(pixelRatio: 2);
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
await File(path).writeAsBytes(data!.buffer.asUint8List(), flush: true);
await File(path).writeAsBytes(bytes, flush: true);
if (mounted) c.setStatus('已导出 $path');
} catch (e) {
if (mounted) await showMessage(context, '导出失败', '$e');
@@ -383,36 +381,16 @@ class _AppShellState extends State<AppShell> {
// 画布舞台:可绘制区域,叠加画布视图与浮层。
child: Stack(
children: <Widget>[
// 导出边界:仅包含「时序图 + 标题」,不含编辑辅助浮层。
// 底层:可交互的画布。
Positioned.fill(
child: RepaintBoundary(
key: _stageKey,
child: Stack(
children: <Widget>[
// 底层:可交互的画布。
Positioned.fill(
child: Container(color: t.canvas2, child: CanvasView(controller: c)),
),
// 仅标题(参与导出)。
Positioned.fill(
child: CanvasOverlays(
controller: c,
leftInset: _leftRail ? 22 : 0,
rightInset: _rightRail ? 22 : 0,
showPanels: false,
),
),
],
),
),
child: Container(color: t.canvas2, child: CanvasView(controller: c)),
),
// 编辑辅助浮层(图例 / 统计 / 工具 / 预览 / 浮动条):不参与导出。
// 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。
Positioned.fill(
child: CanvasOverlays(
controller: c,
leftInset: _leftRail ? 22 : 0,
rightInset: _rightRail ? 22 : 0,
showTitle: false,
),
),
// 收起状态:贴边轨道(悬停可展开为悬浮面板)。
+132 -10
View File
@@ -422,10 +422,99 @@ Future<String?> pickFile(
// ===================== 安卓公共 Documents 文件对话框 =====================
/// 安卓版文件对话框:保存到 / 打开自公共 `Documents/SequenceDiagram`。
/// 保存位置设置:选择基础目录(文档 / 下载 / 图片)与子文件夹名。
class SaveLocationDialog extends StatefulWidget {
const SaveLocationDialog({super.key});
@override
State<SaveLocationDialog> createState() => _SaveLocationDialogState();
}
class _SaveLocationDialogState extends State<SaveLocationDialog> {
late String _base;
late TextEditingController _folder;
static String zh(String b) => switch (b) {
'downloads' => '下载',
'pictures' => '图片',
_ => '文档',
};
@override
void initState() {
super.initState();
final Map<String, String> s = AndroidDocs.settings();
_base = s['base'] ?? 'documents';
_folder = TextEditingController(text: s['folder'] ?? 'SequenceDiagram');
}
@override
void dispose() {
_folder.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: const Text('保存位置'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('基础目录', style: TextStyle(color: t.sub, fontSize: 12)),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: AndroidDocs.baseOptions.map((String b) {
return ChoiceChip(
label: Text(zh(b)),
selected: _base == b,
onSelected: (_) => setState(() => _base = b),
);
}).toList(),
),
const SizedBox(height: 14),
Text('子文件夹名称', style: TextStyle(color: t.sub, fontSize: 12)),
const SizedBox(height: 8),
TextField(
controller: _folder,
style: TextStyle(color: t.text, fontSize: 12.5),
decoration: InputDecoration(
isDense: true,
filled: true,
fillColor: t.panel2,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
),
),
const SizedBox(height: 10),
Text('保存、导出、打开都使用该目录;位于平板「文件管理」可见的公共存储。',
style: TextStyle(color: t.dim, fontSize: 11, height: 1.5)),
],
),
),
actions: <Widget>[
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () async {
await AndroidDocs.saveSettings(_base, _folder.text);
if (context.mounted) Navigator.pop(context);
},
child: const Text('确定'),
),
],
);
}
}
/// 安卓版文件对话框:保存到 / 打开自配置的公共目录(默认 Documents/SequenceDiagram)。
///
/// - 保存模式:输入文件名(自动补全后缀),确认后由调用方经 [AndroidDocs] 写入;
/// - 打开模式:列出 Documents 目录中匹配后缀的文件,点选返回文件名。
/// - 保存模式:显示当前保存位置(可点「更改位置」修改),输入文件名自动补全后缀;
/// - 打开模式:列出目录中匹配后缀的文件,点选返回文件名。
/// 返回值为文件名;取消返回 null。
class AndroidFileDialog extends StatefulWidget {
const AndroidFileDialog({
@@ -465,7 +554,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
super.dispose();
}
/// 列出 Documents 目录中的匹配文件(新在前)。
/// 列出配置目录中的匹配文件(新在前)。
Future<void> _load() async {
setState(() {
_loading = true;
@@ -479,7 +568,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
.toList();
if (mounted) setState(() => _files = matched);
} catch (e) {
if (mounted) setState(() => _error = '无法读取 Documents 目录:$e');
if (mounted) setState(() => _error = '无法读取目录:$e');
} finally {
if (mounted) setState(() => _loading = false);
}
@@ -500,21 +589,52 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
return '$n${widget.suffix}';
}
/// 「更改位置」按钮:打开保存位置设置,返回后刷新本对话框。
Future<void> _changeLocation() async {
await showDialog<void>(context: context, builder: (_) => const SaveLocationDialog());
if (!mounted) return;
setState(() {});
if (!widget.saveMode) _load();
}
/// 当前保存位置展示行。
Widget _locationRow(Tokens t) {
return Row(
children: <Widget>[
Icon(Icons.folder_outlined, size: 15, color: t.accent),
const SizedBox(width: 6),
Expanded(
child: Text('平板存储 / ${AndroidDocs.location()} /',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: t.dim, fontSize: 11)),
),
TextButton(
onPressed: _changeLocation,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 8),
minimumSize: const Size(0, 28),
),
child: const Text('更改位置', style: TextStyle(fontSize: 12)),
),
],
);
}
@override
Widget build(BuildContext context) {
final Tokens t = context.tok;
return AlertDialog(
backgroundColor: t.dialog,
title: Text(widget.saveMode ? '保存到 Documents' : '从 Documents 打开'),
title: Text(widget.saveMode ? '保存到公共目录' : '从公共目录打开'),
content: SizedBox(
width: 420,
width: 460,
child: widget.saveMode
? Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('文件将保存到平板存储的 ${AndroidDocs.displayDir}/',
style: TextStyle(color: t.dim, fontSize: 11)),
_locationRow(t),
const SizedBox(height: 10),
TextField(
controller: _name,
@@ -533,6 +653,8 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
_locationRow(t),
const SizedBox(height: 6),
if (_loading)
const Padding(
padding: EdgeInsets.all(16),
@@ -546,7 +668,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
else if (_files.isEmpty)
Padding(
padding: const EdgeInsets.all(14),
child: Text('Documents 目录中暂无 ${widget.suffix} 文件',
child: Text('目录中暂无 ${widget.suffix} 文件',
style: TextStyle(color: t.dim, fontSize: 11.5)),
)
else