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:
+10
-4
@@ -152,13 +152,19 @@ flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-
|
|||||||
### 平台差异说明
|
### 平台差异说明
|
||||||
|
|
||||||
- **license**:`LicenseService.init()` 在非 Windows 平台直接判定已授权,Android 版无授权限制。
|
- **license**:`LicenseService.init()` 在非 Windows 平台直接判定已授权,Android 版无授权限制。
|
||||||
- **文件保存(安卓)**:保存工程 / 导出 SVG / PNG 统一写入系统公共
|
- **文件保存(安卓)**:保存工程 / 导出 SVG / PNG 写入公共目录(平板文件管理器可见),
|
||||||
**`Documents/SequenceDiagram/`**(平板文件管理器可见):
|
**位置可在应用内修改**(保存/打开对话框里的「更改位置」):
|
||||||
|
- 基础目录可选 **文档 / 下载 / 图片**,子文件夹名可自定义(默认 `SequenceDiagram`);
|
||||||
|
- 设置保存在应用私有目录 `save_location.json`,跨会话生效;
|
||||||
- Android 10+ 通过 MediaStore 写入(无需存储权限,商店合规);
|
- Android 10+ 通过 MediaStore 写入(无需存储权限,商店合规);
|
||||||
- Android 9 及以下直接写公共目录(manifest 中 `WRITE_EXTERNAL_STORAGE` 限 maxSdkVersion=28);
|
- Android 9 及以下直接写公共目录(manifest 中 `WRITE_EXTERNAL_STORAGE` 限 maxSdkVersion=28)。
|
||||||
- 「打开」从 Documents/SequenceDiagram 选择 `.seq.json`。
|
|
||||||
- 原生实现:`android/app/src/main/kotlin/.../MainActivity.kt`(通道 `seqstudio/docs`),
|
- 原生实现:`android/app/src/main/kotlin/.../MainActivity.kt`(通道 `seqstudio/docs`),
|
||||||
Dart 侧封装见 `lib/persistence/android_docs.dart`。
|
Dart 侧封装见 `lib/persistence/android_docs.dart`。
|
||||||
|
- **导出格式(Windows 与 Android 一致)**:
|
||||||
|
- 固定画布 **1920×1080**(SVG `viewBox` 同步);
|
||||||
|
- **标题固定在左上角**、图例固定在左下角;
|
||||||
|
- 时序图内容按自身包围盒**等比缩放并居中**到内容区,不裁切、不溢出
|
||||||
|
(`lib/export/export_fit.dart` 统一计算,PNG 渲染器与 SVG 写入器共用)。
|
||||||
- **桌面(Windows)文件保存**:仍使用应用内文件浏览器,默认起始目录为桌面,
|
- **桌面(Windows)文件保存**:仍使用应用内文件浏览器,默认起始目录为桌面,
|
||||||
并跨会话记忆上次使用的目录。
|
并跨会话记忆上次使用的目录。
|
||||||
- **自动保存**:安卓落于应用私有缓存目录(仅用于崩溃恢复,不对外可见)。
|
- **自动保存**:安卓落于应用私有缓存目录(仅用于崩溃恢复,不对外可见)。
|
||||||
|
|||||||
@@ -91,7 +91,8 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模
|
|||||||
|
|
||||||
- **目标分辨率**:1280×800dp(2560×1600 物理),并动态兼容其它横竖屏分辨率;
|
- **目标分辨率**:1280×800dp(2560×1600 物理),并动态兼容其它横竖屏分辨率;
|
||||||
- **无 license 授权**(面向应用商店分发);包名 `cc.sincos.sequence_diagram`,应用名「时序图设计器」;
|
- **无 license 授权**(面向应用商店分发);包名 `cc.sincos.sequence_diagram`,应用名「时序图设计器」;
|
||||||
- **文件保存**:工程 / SVG / PNG 统一保存到平板可见的 **`Documents/SequenceDiagram/`**(Android 10+ 走 MediaStore,无需权限);
|
- **文件保存**:工程 / SVG / PNG 保存到平板可见的公共目录(默认 `Documents/SequenceDiagram`,可在保存对话框「更改位置」中选择文档/下载/图片 + 自定义子文件夹;Android 10+ 走 MediaStore,无需权限);
|
||||||
|
- **导出格式**:固定 **1920×1080**,标题恒定左上、图例恒定左下,内容按包围盒自适应缩放居中(SVG / PNG 一致,exe 与安卓一致);
|
||||||
- **触控手势**:画布支持**双指捏合缩放 / 双指平移**(以捏合焦点为锚点),单指拖拽编辑不变;全屏无黑边(状态栏/导航栏区域融入界面);
|
- **触控手势**:画布支持**双指捏合缩放 / 双指平移**(以捏合焦点为锚点),单指拖拽编辑不变;全屏无黑边(状态栏/导航栏区域融入界面);
|
||||||
- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装;
|
- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装;
|
||||||
- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像:
|
- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像:
|
||||||
|
|||||||
@@ -12,16 +12,16 @@ import java.io.File
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 安卓公共文档读写通道(`seqstudio/docs`):
|
* 安卓公共文档读写通道(`seqstudio/docs`):
|
||||||
* 保存 / 列出 / 读取 `Documents/SequenceDiagram` 下的文件。
|
* 保存 / 列出 / 读取配置目录(默认 `Documents/SequenceDiagram`,可在应用内修改为
|
||||||
|
* Download / Pictures + 自定义子文件夹)下的文件。
|
||||||
*
|
*
|
||||||
* - API 29+(Android 10+):通过 MediaStore 写入公共 Documents,
|
* - API 29+(Android 10+):通过 MediaStore 写入公共目录,
|
||||||
* 无需存储权限,符合应用商店的分区存储(scoped storage)要求;
|
* 无需存储权限,符合应用商店的分区存储(scoped storage)要求;
|
||||||
* - API ≤ 28:直接写入公共目录(配合 manifest 中 maxSdkVersion=28 的
|
* - API ≤ 28:直接写入公共目录(配合 manifest 中 maxSdkVersion=28 的
|
||||||
* WRITE_EXTERNAL_STORAGE 权限)。
|
* WRITE_EXTERNAL_STORAGE 权限)。
|
||||||
*/
|
*/
|
||||||
class MainActivity : FlutterActivity() {
|
class MainActivity : FlutterActivity() {
|
||||||
private val channelName = "seqstudio/docs"
|
private val channelName = "seqstudio/docs"
|
||||||
private val folderName = "SequenceDiagram"
|
|
||||||
|
|
||||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||||
super.configureFlutterEngine(flutterEngine)
|
super.configureFlutterEngine(flutterEngine)
|
||||||
@@ -32,30 +32,36 @@ class MainActivity : FlutterActivity() {
|
|||||||
val name = call.argument<String>("name")
|
val name = call.argument<String>("name")
|
||||||
val data = call.argument<ByteArray>("data")
|
val data = call.argument<ByteArray>("data")
|
||||||
val mime = call.argument<String>("mime")
|
val mime = call.argument<String>("mime")
|
||||||
|
val base = call.argument<String>("base") ?: "documents"
|
||||||
|
val folder = call.argument<String>("folder") ?: "SequenceDiagram"
|
||||||
if (name == null || data == null) {
|
if (name == null || data == null) {
|
||||||
result.error("ARGS", "name/data required", null)
|
result.error("ARGS", "name/data required", null)
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
result.success(saveFile(name, data, mime))
|
result.success(saveFile(base, folder, name, data, mime))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
result.error("WRITE", e.message, null)
|
result.error("WRITE", e.message, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"listFiles" -> {
|
"listFiles" -> {
|
||||||
|
val base = call.argument<String>("base") ?: "documents"
|
||||||
|
val folder = call.argument<String>("folder") ?: "SequenceDiagram"
|
||||||
try {
|
try {
|
||||||
result.success(listFiles())
|
result.success(listFiles(base, folder))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
result.error("LIST", e.message, null)
|
result.error("LIST", e.message, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"readFile" -> {
|
"readFile" -> {
|
||||||
val name = call.argument<String>("name")
|
val name = call.argument<String>("name")
|
||||||
|
val base = call.argument<String>("base") ?: "documents"
|
||||||
|
val folder = call.argument<String>("folder") ?: "SequenceDiagram"
|
||||||
if (name == null) {
|
if (name == null) {
|
||||||
result.error("ARGS", "name required", null)
|
result.error("ARGS", "name required", null)
|
||||||
} else {
|
} else {
|
||||||
try {
|
try {
|
||||||
result.success(readFile(name))
|
result.success(readFile(base, folder, name))
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
result.error("READ", e.message, null)
|
result.error("READ", e.message, null)
|
||||||
}
|
}
|
||||||
@@ -66,29 +72,36 @@ class MainActivity : FlutterActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 把 base 关键字映射为系统的公共目录常量。 */
|
||||||
|
private fun envDir(base: String): String = when (base) {
|
||||||
|
"downloads" -> Environment.DIRECTORY_DOWNLOADS
|
||||||
|
"pictures" -> Environment.DIRECTORY_PICTURES
|
||||||
|
else -> Environment.DIRECTORY_DOCUMENTS
|
||||||
|
}
|
||||||
|
|
||||||
/** MediaStore 相对路径(Q+);API ≤ 28 返回绝对路径。 */
|
/** MediaStore 相对路径(Q+);API ≤ 28 返回绝对路径。 */
|
||||||
private fun documentsFolder(): String {
|
private fun folderPath(base: String, folder: String): String {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
return Environment.DIRECTORY_DOCUMENTS + "/" + folderName
|
return envDir(base) + "/" + folder
|
||||||
}
|
}
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val dir = File(
|
val dir = File(
|
||||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
Environment.getExternalStoragePublicDirectory(envDir(base)),
|
||||||
folderName,
|
folder,
|
||||||
)
|
)
|
||||||
if (!dir.exists()) dir.mkdirs()
|
if (!dir.exists()) dir.mkdirs()
|
||||||
return dir.absolutePath
|
return dir.absolutePath
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 保存文件到公共 Documents/SequenceDiagram,返回用于展示的位置。 */
|
/** 保存文件到配置的公共目录,返回用于展示的位置。 */
|
||||||
private fun saveFile(name: String, data: ByteArray, mime: String?): String {
|
private fun saveFile(base: String, folder: String, name: String, data: ByteArray, mime: String?): String {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
val resolver = contentResolver
|
val resolver = contentResolver
|
||||||
val collection = MediaStore.Files.getContentUri("external_primary")
|
val collection = MediaStore.Files.getContentUri("external_primary")
|
||||||
val values = ContentValues().apply {
|
val values = ContentValues().apply {
|
||||||
put(MediaStore.Files.FileColumns.DISPLAY_NAME, name)
|
put(MediaStore.Files.FileColumns.DISPLAY_NAME, name)
|
||||||
put(MediaStore.Files.FileColumns.MIME_TYPE, mime ?: "application/octet-stream")
|
put(MediaStore.Files.FileColumns.MIME_TYPE, mime ?: "application/octet-stream")
|
||||||
put(MediaStore.Files.FileColumns.RELATIVE_PATH, documentsFolder())
|
put(MediaStore.Files.FileColumns.RELATIVE_PATH, folderPath(base, folder))
|
||||||
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
|
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
|
||||||
}
|
}
|
||||||
val uri: Uri = resolver.insert(collection, values)
|
val uri: Uri = resolver.insert(collection, values)
|
||||||
@@ -98,20 +111,20 @@ class MainActivity : FlutterActivity() {
|
|||||||
values.clear()
|
values.clear()
|
||||||
values.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
|
values.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
|
||||||
resolver.update(uri, values, null, null)
|
resolver.update(uri, values, null, null)
|
||||||
return "Documents/$folderName/$name"
|
return "${envDir(base)}/$folder/$name"
|
||||||
}
|
}
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val dir = File(
|
val dir = File(
|
||||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
Environment.getExternalStoragePublicDirectory(envDir(base)),
|
||||||
folderName,
|
folder,
|
||||||
)
|
)
|
||||||
if (!dir.exists()) dir.mkdirs()
|
if (!dir.exists()) dir.mkdirs()
|
||||||
File(dir, name).writeBytes(data)
|
File(dir, name).writeBytes(data)
|
||||||
return "Documents/$folderName/$name"
|
return "${envDir(base)}/$folder/$name"
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 列出 Documents/SequenceDiagram 下的文件([{name, size}],新在前)。 */
|
/** 列出配置目录下的文件([{name, size}],新在前)。 */
|
||||||
private fun listFiles(): List<Map<String, Any>> {
|
private fun listFiles(base: String, folder: String): List<Map<String, Any>> {
|
||||||
val out = mutableListOf<Map<String, Any>>()
|
val out = mutableListOf<Map<String, Any>>()
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
val resolver = contentResolver
|
val resolver = contentResolver
|
||||||
@@ -122,7 +135,7 @@ class MainActivity : FlutterActivity() {
|
|||||||
MediaStore.Files.FileColumns.SIZE,
|
MediaStore.Files.FileColumns.SIZE,
|
||||||
)
|
)
|
||||||
val selection = "${MediaStore.Files.FileColumns.RELATIVE_PATH}=?"
|
val selection = "${MediaStore.Files.FileColumns.RELATIVE_PATH}=?"
|
||||||
val args = arrayOf(documentsFolder() + "/")
|
val args = arrayOf(folderPath(base, folder) + "/")
|
||||||
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
||||||
val iName = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
|
val iName = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
|
||||||
val iSize = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
|
val iSize = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
|
||||||
@@ -133,8 +146,8 @@ class MainActivity : FlutterActivity() {
|
|||||||
} else {
|
} else {
|
||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val dir = File(
|
val dir = File(
|
||||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
Environment.getExternalStoragePublicDirectory(envDir(base)),
|
||||||
folderName,
|
folder,
|
||||||
)
|
)
|
||||||
if (dir.exists()) {
|
if (dir.exists()) {
|
||||||
dir.listFiles()?.sortedByDescending { it.lastModified() }?.forEach {
|
dir.listFiles()?.sortedByDescending { it.lastModified() }?.forEach {
|
||||||
@@ -145,8 +158,8 @@ class MainActivity : FlutterActivity() {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 读取 Documents/SequenceDiagram 下的文件内容;不存在返回 null。 */
|
/** 读取配置目录下的文件内容;不存在返回 null。 */
|
||||||
private fun readFile(name: String): ByteArray? {
|
private fun readFile(base: String, folder: String, name: String): ByteArray? {
|
||||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||||
val resolver = contentResolver
|
val resolver = contentResolver
|
||||||
val collection = MediaStore.Files.getContentUri("external_primary")
|
val collection = MediaStore.Files.getContentUri("external_primary")
|
||||||
@@ -154,7 +167,7 @@ class MainActivity : FlutterActivity() {
|
|||||||
val selection =
|
val selection =
|
||||||
"${MediaStore.Files.FileColumns.RELATIVE_PATH}=? AND " +
|
"${MediaStore.Files.FileColumns.RELATIVE_PATH}=? AND " +
|
||||||
"${MediaStore.Files.FileColumns.DISPLAY_NAME}=?"
|
"${MediaStore.Files.FileColumns.DISPLAY_NAME}=?"
|
||||||
val args = arrayOf(documentsFolder() + "/", name)
|
val args = arrayOf(folderPath(base, folder) + "/", name)
|
||||||
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
||||||
if (c.moveToFirst()) {
|
if (c.moveToFirst()) {
|
||||||
val uri = Uri.withAppendedPath(collection, c.getLong(0).toString())
|
val uri = Uri.withAppendedPath(collection, c.getLong(0).toString())
|
||||||
@@ -166,8 +179,8 @@ class MainActivity : FlutterActivity() {
|
|||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
val f = File(
|
val f = File(
|
||||||
File(
|
File(
|
||||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
Environment.getExternalStoragePublicDirectory(envDir(base)),
|
||||||
folderName,
|
folder,
|
||||||
),
|
),
|
||||||
name,
|
name,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -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°';
|
||||||
@@ -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
@@ -10,8 +10,10 @@
|
|||||||
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
|
/// - 每个逻辑分组写成 `<g id="...">`(背景、标尺、动作、标签、依赖、图例),
|
||||||
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
|
/// 动作组与依赖组额外附带 `data-*` 属性,便于下游脚本解析。
|
||||||
///
|
///
|
||||||
/// 输出约定:
|
/// 输出约定(与 PNG 导出一致):
|
||||||
/// - 画布固定 2560×1440,通过 `viewBox` 支持无损缩放。
|
/// - 画布固定 1920×1080,通过 `viewBox` 支持无损缩放;
|
||||||
|
/// - 标题固定在左上角、图例固定在左下角;
|
||||||
|
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
|
||||||
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
|
/// - 所有文本内联 [_font] 字体栈,保证跨平台字形一致。
|
||||||
library;
|
library;
|
||||||
|
|
||||||
@@ -22,6 +24,7 @@ import '../layout/layout.dart';
|
|||||||
import '../model/models.dart';
|
import '../model/models.dart';
|
||||||
import '../model/units.dart';
|
import '../model/units.dart';
|
||||||
import '../theme/tokens.dart';
|
import '../theme/tokens.dart';
|
||||||
|
import 'export_fit.dart';
|
||||||
|
|
||||||
/// SVG 文档写入器。
|
/// SVG 文档写入器。
|
||||||
///
|
///
|
||||||
@@ -51,28 +54,42 @@ class SvgWriter {
|
|||||||
|
|
||||||
/// 生成完整 SVG 文档字符串。
|
/// 生成完整 SVG 文档字符串。
|
||||||
///
|
///
|
||||||
|
/// 输出约定(与 PNG 导出一致):
|
||||||
|
/// - 画布固定 1920×1080;
|
||||||
|
/// - 标题固定在左上角、图例固定在左下角;
|
||||||
|
/// - 时序图内容按自身包围盒等比缩放并居中到内容区,不裁切、不溢出。
|
||||||
|
///
|
||||||
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
|
/// 返回:以 `<svg ...>` 开头、`</svg>` 结尾的字符串。
|
||||||
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
|
/// 副作用:会持续向内部缓冲区追加内容;重复调用不会自动清空缓冲区,
|
||||||
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
|
/// 因此约定每次导出都新建一个 [SvgWriter] 实例。
|
||||||
String build() {
|
String build() {
|
||||||
// 固定逻辑画布尺寸;viewBox 与 width/height 相同,缩放时几何不失真。
|
const double w = 1920;
|
||||||
final double w = 2560;
|
const double h = 1080;
|
||||||
final double h = 1440;
|
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">');
|
||||||
_b.write('<svg xmlns="http://www.w3.org/2000/svg" width="$w" height="$h" viewBox="0 0 $w $h">');
|
|
||||||
// 先写箭头 marker 定义,供后续依赖路径引用。
|
// 先写箭头 marker 定义,供后续依赖路径引用。
|
||||||
_defs();
|
_defs();
|
||||||
// 背景层:铺满整张画布。
|
// 背景层:铺满整张画布。
|
||||||
_b.write('<g id="background">');
|
_b.write('<g id="background">');
|
||||||
_rect(0, 0, w, h, fill: _hex(tokens.bg));
|
_rect(0, 0, w, h, fill: _hex(tokens.bg));
|
||||||
_b.write('</g>');
|
_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) {
|
if (mode == ViewMode.bar) {
|
||||||
_barView(Size(w, h));
|
_barView(const Size(w, h));
|
||||||
} else {
|
} else {
|
||||||
_circularView(Size(w, h));
|
_circularView(const Size(w, h));
|
||||||
}
|
}
|
||||||
// 图例始终绘制在最上层。
|
_b.write('</g>');
|
||||||
_legend(w, h);
|
// 图例:固定左下角。
|
||||||
|
_b.write('<g id="legend">');
|
||||||
|
_text(48, h - 36, exportLegend(project), color: _hex(tokens.sub), size: 15);
|
||||||
|
_b.write('</g>');
|
||||||
_b.write('</svg>');
|
_b.write('</svg>');
|
||||||
return _b.toString();
|
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` 路径字符串。
|
/// 生成一段圆弧的 SVG `d` 路径字符串。
|
||||||
///
|
///
|
||||||
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
|
/// 参数 [c] 圆心、[r] 半径、[a0]/[a1] 起止角度(度)。
|
||||||
|
|||||||
@@ -1,17 +1,23 @@
|
|||||||
/// 安卓公共 Documents(Documents/SequenceDiagram)读写服务。
|
/// 安卓公共存储读写服务。
|
||||||
///
|
///
|
||||||
/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现:
|
/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现:
|
||||||
/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规);
|
/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规);
|
||||||
/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。
|
/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。
|
||||||
///
|
///
|
||||||
|
/// 保存位置可配置:基础目录(Documents / Download / Pictures)+ 子文件夹名,
|
||||||
|
/// 设置保存在应用私有目录的 `save_location.json`,跨会话生效。
|
||||||
|
///
|
||||||
/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。
|
/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。
|
||||||
library;
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
/// 安卓公共文档读写。
|
import 'storage.dart';
|
||||||
|
|
||||||
|
/// 安卓公共存储读写。
|
||||||
class AndroidDocs {
|
class AndroidDocs {
|
||||||
AndroidDocs._();
|
AndroidDocs._();
|
||||||
|
|
||||||
@@ -21,34 +27,92 @@ class AndroidDocs {
|
|||||||
/// 是否可用(仅 Android)。
|
/// 是否可用(仅 Android)。
|
||||||
static bool get isAvailable => Platform.isAndroid;
|
static bool get isAvailable => Platform.isAndroid;
|
||||||
|
|
||||||
/// 用于展示的目录描述。
|
/// 可选的基础目录:文档 / 下载 / 图片。
|
||||||
static const String displayDir = 'Documents/SequenceDiagram';
|
static const List<String> baseOptions = <String>['documents', 'downloads', 'pictures'];
|
||||||
|
|
||||||
/// 保存文件到公共 Documents/SequenceDiagram,返回展示位置。
|
/// 基础目录的展示名。
|
||||||
///
|
static String baseLabel(String base) => switch (base) {
|
||||||
/// 参数 [name] 文件名(含后缀);[data] 文件内容;[mime] 可选 MIME 类型。
|
'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 {
|
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?>{
|
final Object? r = await _channel.invokeMethod<Object?>('saveFile', <String, Object?>{
|
||||||
'name': name,
|
'name': name,
|
||||||
'data': data,
|
'data': data,
|
||||||
'mime': mime,
|
'mime': mime,
|
||||||
|
'base': s['base'],
|
||||||
|
'folder': s['folder'],
|
||||||
});
|
});
|
||||||
return r as String;
|
return r as String;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 列出 Documents/SequenceDiagram 下的文件(`[{name, size}]`,新在前)。
|
/// 列出配置目录下的文件(`[{name, size}]`,新在前)。
|
||||||
static Future<List<Map<String, dynamic>>> listFiles() async {
|
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?>[];
|
final List<Object?> list = (r as List<Object?>?) ?? const <Object?>[];
|
||||||
return list
|
return list
|
||||||
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
|
.map((Object? e) => Map<String, dynamic>.from(e as Map<Object?, Object?>))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 读取 Documents/SequenceDiagram 下的文件内容;不存在返回 null。
|
/// 读取配置目录下的文件内容;不存在返回 null。
|
||||||
static Future<Uint8List?> readFile(String name) async {
|
static Future<Uint8List?> readFile(String name) async {
|
||||||
|
final Map<String, String> s = settings();
|
||||||
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
|
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
|
||||||
'name': name,
|
'name': name,
|
||||||
|
'base': s['base'],
|
||||||
|
'folder': s['folder'],
|
||||||
});
|
});
|
||||||
if (r == null) return null;
|
if (r == null) return null;
|
||||||
return r as Uint8List;
|
return r as Uint8List;
|
||||||
|
|||||||
+23
-45
@@ -11,12 +11,11 @@
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
import 'dart:math' as math;
|
import 'dart:math' as math;
|
||||||
import 'dart:ui' as ui;
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart' hide Action;
|
import 'package:flutter/material.dart' hide Action;
|
||||||
import 'package:flutter/rendering.dart';
|
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
|
||||||
|
import '../export/export_renderer.dart';
|
||||||
import '../export/svg_writer.dart';
|
import '../export/svg_writer.dart';
|
||||||
import '../model/models.dart';
|
import '../model/models.dart';
|
||||||
import '../model/units.dart';
|
import '../model/units.dart';
|
||||||
@@ -45,9 +44,6 @@ class AppShell extends StatefulWidget {
|
|||||||
/// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态,
|
/// 应用外壳状态:维护左右侧栏的可见性、钉住与悬浮状态,
|
||||||
/// 并提供文件操作、导出与快捷键处理。
|
/// 并提供文件操作、导出与快捷键处理。
|
||||||
class _AppShellState extends State<AppShell> {
|
class _AppShellState extends State<AppShell> {
|
||||||
/// 画布舞台的绘制边界 key,用于 PNG 导出时抓取像素。
|
|
||||||
final GlobalKey _stageKey = GlobalKey();
|
|
||||||
|
|
||||||
// ---- 侧栏状态机:可见(visible) × 钉住(pinned) × 悬停(hover) ----
|
// ---- 侧栏状态机:可见(visible) × 钉住(pinned) × 悬停(hover) ----
|
||||||
/// 左侧栏是否可见。
|
/// 左侧栏是否可见。
|
||||||
bool _leftVisible = true;
|
bool _leftVisible = true;
|
||||||
@@ -170,7 +166,7 @@ class _AppShellState extends State<AppShell> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
c.loadProject(Project.decode(utf8.decode(bytes)), path: null);
|
c.loadProject(Project.decode(utf8.decode(bytes)), path: null);
|
||||||
c.setStatus('已打开 ${AndroidDocs.displayDir}/$name');
|
c.setStatus('已打开 ${AndroidDocs.location()}/$name');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (mounted) await showMessage(context, '打开失败', '$e');
|
if (mounted) await showMessage(context, '打开失败', '$e');
|
||||||
}
|
}
|
||||||
@@ -212,7 +208,7 @@ class _AppShellState extends State<AppShell> {
|
|||||||
try {
|
try {
|
||||||
final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode()));
|
final Uint8List data = Uint8List.fromList(utf8.encode(c.project.encode()));
|
||||||
await AndroidDocs.saveFile(name, data, mime: 'application/json');
|
await AndroidDocs.saveFile(name, data, mime: 'application/json');
|
||||||
await c.markSaved('${AndroidDocs.displayDir}/$name');
|
await c.markSaved('${AndroidDocs.location()}/$name');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (mounted) await showMessage(context, '保存失败', '$e');
|
if (mounted) await showMessage(context, '保存失败', '$e');
|
||||||
}
|
}
|
||||||
@@ -258,7 +254,7 @@ class _AppShellState extends State<AppShell> {
|
|||||||
mode: c.project.viewState.mode,
|
mode: c.project.viewState.mode,
|
||||||
).build();
|
).build();
|
||||||
await AndroidDocs.saveFile(name, Uint8List.fromList(utf8.encode(svg)), mime: 'image/svg+xml');
|
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) {
|
} catch (e) {
|
||||||
if (mounted) await showMessage(context, '导出失败', '$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 {
|
Future<void> _exportPng() async {
|
||||||
if (!c.licensed) {
|
if (!c.licensed) {
|
||||||
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
|
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
|
||||||
return;
|
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) {
|
if (AndroidDocs.isAvailable) {
|
||||||
final String? name = await showDialog<String>(
|
final String? name = await showDialog<String>(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -303,13 +311,8 @@ class _AppShellState extends State<AppShell> {
|
|||||||
);
|
);
|
||||||
if (name == null) return;
|
if (name == null) return;
|
||||||
try {
|
try {
|
||||||
// 抓取画布舞台的渲染对象并转换为图像。
|
await AndroidDocs.saveFile(name, bytes, mime: 'image/png');
|
||||||
final RenderRepaintBoundary boundary =
|
if (mounted) c.setStatus('已导出 ${AndroidDocs.location()}/$name');
|
||||||
_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');
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||||
}
|
}
|
||||||
@@ -323,12 +326,7 @@ class _AppShellState extends State<AppShell> {
|
|||||||
);
|
);
|
||||||
if (path == null) return;
|
if (path == null) return;
|
||||||
try {
|
try {
|
||||||
// 抓取画布舞台的渲染对象并转换为图像。
|
await File(path).writeAsBytes(bytes, flush: true);
|
||||||
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);
|
|
||||||
if (mounted) c.setStatus('已导出 $path');
|
if (mounted) c.setStatus('已导出 $path');
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||||
@@ -381,38 +379,18 @@ class _AppShellState extends State<AppShell> {
|
|||||||
if (_leftDocked) _leftPanel(t),
|
if (_leftDocked) _leftPanel(t),
|
||||||
Expanded(
|
Expanded(
|
||||||
// 画布舞台:可绘制区域,叠加画布视图与浮层。
|
// 画布舞台:可绘制区域,叠加画布视图与浮层。
|
||||||
child: Stack(
|
|
||||||
children: <Widget>[
|
|
||||||
// 导出边界:仅包含「时序图 + 标题」,不含编辑辅助浮层。
|
|
||||||
Positioned.fill(
|
|
||||||
child: RepaintBoundary(
|
|
||||||
key: _stageKey,
|
|
||||||
child: Stack(
|
child: Stack(
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
// 底层:可交互的画布。
|
// 底层:可交互的画布。
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: Container(color: t.canvas2, child: CanvasView(controller: c)),
|
child: Container(color: t.canvas2, child: CanvasView(controller: c)),
|
||||||
),
|
),
|
||||||
// 仅标题(参与导出)。
|
// 浮层:标题 / 图例 / 统计 / 工具 / 预览 / 浮动条。
|
||||||
Positioned.fill(
|
Positioned.fill(
|
||||||
child: CanvasOverlays(
|
child: CanvasOverlays(
|
||||||
controller: c,
|
controller: c,
|
||||||
leftInset: _leftRail ? 22 : 0,
|
leftInset: _leftRail ? 22 : 0,
|
||||||
rightInset: _rightRail ? 22 : 0,
|
rightInset: _rightRail ? 22 : 0,
|
||||||
showPanels: false,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
// 编辑辅助浮层(图例 / 统计 / 工具 / 预览 / 浮动条):不参与导出。
|
|
||||||
Positioned.fill(
|
|
||||||
child: CanvasOverlays(
|
|
||||||
controller: c,
|
|
||||||
leftInset: _leftRail ? 22 : 0,
|
|
||||||
rightInset: _rightRail ? 22 : 0,
|
|
||||||
showTitle: false,
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
// 收起状态:贴边轨道(悬停可展开为悬浮面板)。
|
// 收起状态:贴边轨道(悬停可展开为悬浮面板)。
|
||||||
|
|||||||
+132
-10
@@ -422,10 +422,99 @@ Future<String?> pickFile(
|
|||||||
|
|
||||||
// ===================== 安卓公共 Documents 文件对话框 =====================
|
// ===================== 安卓公共 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。
|
/// 返回值为文件名;取消返回 null。
|
||||||
class AndroidFileDialog extends StatefulWidget {
|
class AndroidFileDialog extends StatefulWidget {
|
||||||
const AndroidFileDialog({
|
const AndroidFileDialog({
|
||||||
@@ -465,7 +554,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 列出 Documents 目录中的匹配文件(新在前)。
|
/// 列出配置目录中的匹配文件(新在前)。
|
||||||
Future<void> _load() async {
|
Future<void> _load() async {
|
||||||
setState(() {
|
setState(() {
|
||||||
_loading = true;
|
_loading = true;
|
||||||
@@ -479,7 +568,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
|||||||
.toList();
|
.toList();
|
||||||
if (mounted) setState(() => _files = matched);
|
if (mounted) setState(() => _files = matched);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (mounted) setState(() => _error = '无法读取 Documents 目录:$e');
|
if (mounted) setState(() => _error = '无法读取目录:$e');
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setState(() => _loading = false);
|
if (mounted) setState(() => _loading = false);
|
||||||
}
|
}
|
||||||
@@ -500,21 +589,52 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
|||||||
return '$n${widget.suffix}';
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final Tokens t = context.tok;
|
final Tokens t = context.tok;
|
||||||
return AlertDialog(
|
return AlertDialog(
|
||||||
backgroundColor: t.dialog,
|
backgroundColor: t.dialog,
|
||||||
title: Text(widget.saveMode ? '保存到 Documents' : '从 Documents 打开'),
|
title: Text(widget.saveMode ? '保存到公共目录' : '从公共目录打开'),
|
||||||
content: SizedBox(
|
content: SizedBox(
|
||||||
width: 420,
|
width: 460,
|
||||||
child: widget.saveMode
|
child: widget.saveMode
|
||||||
? Column(
|
? Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
Text('文件将保存到平板存储的 ${AndroidDocs.displayDir}/',
|
_locationRow(t),
|
||||||
style: TextStyle(color: t.dim, fontSize: 11)),
|
|
||||||
const SizedBox(height: 10),
|
const SizedBox(height: 10),
|
||||||
TextField(
|
TextField(
|
||||||
controller: _name,
|
controller: _name,
|
||||||
@@ -533,6 +653,8 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
|||||||
: Column(
|
: Column(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
|
_locationRow(t),
|
||||||
|
const SizedBox(height: 6),
|
||||||
if (_loading)
|
if (_loading)
|
||||||
const Padding(
|
const Padding(
|
||||||
padding: EdgeInsets.all(16),
|
padding: EdgeInsets.all(16),
|
||||||
@@ -546,7 +668,7 @@ class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
|||||||
else if (_files.isEmpty)
|
else if (_files.isEmpty)
|
||||||
Padding(
|
Padding(
|
||||||
padding: const EdgeInsets.all(14),
|
padding: const EdgeInsets.all(14),
|
||||||
child: Text('Documents 目录中暂无 ${widget.suffix} 文件',
|
child: Text('目录中暂无 ${widget.suffix} 文件',
|
||||||
style: TextStyle(color: t.dim, fontSize: 11.5)),
|
style: TextStyle(color: t.dim, fontSize: 11.5)),
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
// 导出回归测试:SVG / PNG 固定 1920×1080、标题恒定、内容自适应缩放。
|
||||||
|
import 'dart:io';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
import 'dart:ui' as ui;
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:sequence_diagram/export/export_renderer.dart';
|
||||||
|
import 'package:sequence_diagram/export/svg_writer.dart';
|
||||||
|
import 'package:sequence_diagram/model/models.dart';
|
||||||
|
import 'package:sequence_diagram/theme/tokens.dart';
|
||||||
|
|
||||||
|
import 'helpers.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('svg export: fixed 1920x1080 + title + fit transform + legend', () {
|
||||||
|
final Project p = demoTiming();
|
||||||
|
final String svg = SvgWriter(project: p, tokens: Tokens.light, mode: ViewMode.bar).build();
|
||||||
|
expect(svg, contains('width="1920" height="1080" viewBox="0 0 1920 1080"'));
|
||||||
|
expect(svg, contains('<g id="title">'));
|
||||||
|
expect(svg, contains('条形时序视图'));
|
||||||
|
expect(svg, contains('<g id="content" transform="'));
|
||||||
|
expect(svg, contains('<g id="legend">'));
|
||||||
|
expect(svg, contains('装配线节拍'));
|
||||||
|
|
||||||
|
final String circ = SvgWriter(project: p, tokens: Tokens.light, mode: ViewMode.circular).build();
|
||||||
|
expect(circ, contains('圆周时序视图'));
|
||||||
|
expect(circ, contains('width="1920" height="1080"'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('png export: renders exactly 1920x1080', () async {
|
||||||
|
final Project p = demoTiming();
|
||||||
|
final Uint8List bytes = await renderExportPng(
|
||||||
|
project: p,
|
||||||
|
tokens: Tokens.light,
|
||||||
|
criticalActions: const <String>{'A1', 'A2'},
|
||||||
|
criticalDeps: const <String>{'A1->A2'},
|
||||||
|
);
|
||||||
|
final ui.ImmutableBuffer buf = await ui.ImmutableBuffer.fromUint8List(bytes);
|
||||||
|
final ui.ImageDescriptor desc = await ui.ImageDescriptor.encoded(buf);
|
||||||
|
expect(desc.width, 1920);
|
||||||
|
expect(desc.height, 1080);
|
||||||
|
File('build/export_preview.png').writeAsBytesSync(bytes);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user