fix(android): 保存/导出写入系统公共 Documents(可见),不再落到应用私有 data 目录
- 原生通道 seqstudio/docs:Android 10+ 走 MediaStore 写入 Documents/SequenceDiagram(免权限、商店合规);Android 9- 直接写公共目录(WRITE_EXTERNAL_STORAGE 限 maxSdk=28) - 安卓保存/打开/导出改用「Documents 对话框」:保存输入文件名(自动补全后缀),打开列出 Documents 中的 .seq.json 点选 - 控制器新增 markSaved(外部通道保存后标记干净);重新构建签名 APK
This commit is contained in:
+12
-3
@@ -152,11 +152,20 @@ flutter build apk --release # 产物:build\app\outputs\flutter-apk\app-
|
||||
### 平台差异说明
|
||||
|
||||
- **license**:`LicenseService.init()` 在非 Windows 平台直接判定已授权,Android 版无授权限制。
|
||||
- **存储**:无 `%APPDATA%`,自动保存与快照落在系统临时目录(应用私有目录);文件浏览器
|
||||
隐藏「桌面 / 盘符」入口。
|
||||
- **文件保存(安卓)**:保存工程 / 导出 SVG / PNG 统一写入系统公共
|
||||
**`Documents/SequenceDiagram/`**(平板文件管理器可见):
|
||||
- Android 10+ 通过 MediaStore 写入(无需存储权限,商店合规);
|
||||
- Android 9 及以下直接写公共目录(manifest 中 `WRITE_EXTERNAL_STORAGE` 限 maxSdkVersion=28);
|
||||
- 「打开」从 Documents/SequenceDiagram 选择 `.seq.json`。
|
||||
- 原生实现:`android/app/src/main/kotlin/.../MainActivity.kt`(通道 `seqstudio/docs`),
|
||||
Dart 侧封装见 `lib/persistence/android_docs.dart`。
|
||||
- **桌面(Windows)文件保存**:仍使用应用内文件浏览器,默认起始目录为桌面,
|
||||
并跨会话记忆上次使用的目录。
|
||||
- **自动保存**:安卓落于应用私有缓存目录(仅用于崩溃恢复,不对外可见)。
|
||||
- **侧栏**:触屏默认收起为贴边把手(点把手直接停靠展开);面板宽度随屏幕动态压缩,
|
||||
窄屏双侧栏停靠也不溢出。
|
||||
- **系统栏**:edge-to-edge + SafeArea,文本缩放固定 1.0,保证平板各分辨率像素级一致。
|
||||
- **系统栏**:edge-to-edge,状态栏/导航栏区域由工具栏/状态栏底色填满(全屏无黑边),
|
||||
图标亮度随深浅主题切换;文本缩放固定 1.0,保证平板各分辨率像素级一致。
|
||||
|
||||
### 自测
|
||||
|
||||
|
||||
@@ -91,7 +91,8 @@ Flutter 3.29+(Desktop) · CustomPainter 自绘 · Riverpod · 不可变模
|
||||
|
||||
- **目标分辨率**:1280×800dp(2560×1600 物理),并动态兼容其它横竖屏分辨率;
|
||||
- **无 license 授权**(面向应用商店分发);包名 `cc.sincos.sequence_diagram`,应用名「时序图设计器」;
|
||||
- **触控手势**:画布支持**双指捏合缩放 / 双指平移**(以捏合焦点为锚点),单指拖拽编辑不变;
|
||||
- **文件保存**:工程 / SVG / PNG 统一保存到平板可见的 **`Documents/SequenceDiagram/`**(Android 10+ 走 MediaStore,无需权限);
|
||||
- **触控手势**:画布支持**双指捏合缩放 / 双指平移**(以捏合焦点为锚点),单指拖拽编辑不变;全屏无黑边(状态栏/导航栏区域融入界面);
|
||||
- **正式签名**:release 用独立 keystore 签名(`android/key/release.jks`,见 `BUILD-NOTES.md`),更新安装无需卸载重装;
|
||||
- **构建**:JDK 17 + Android SDK 36(详见 `BUILD-NOTES.md`),Gradle 与 Maven 已配置国内镜像:
|
||||
```bash
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- 仅 Android 9 及以下直接写公共目录需要;Android 10+ 走 MediaStore 无需权限。 -->
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="28" />
|
||||
<application
|
||||
android:label="时序图设计器"
|
||||
android:name="${applicationName}"
|
||||
|
||||
@@ -1,5 +1,176 @@
|
||||
package cc.sincos.sequence_diagram
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.io.File
|
||||
|
||||
class MainActivity : FlutterActivity()
|
||||
/**
|
||||
* 安卓公共文档读写通道(`seqstudio/docs`):
|
||||
* 保存 / 列出 / 读取 `Documents/SequenceDiagram` 下的文件。
|
||||
*
|
||||
* - API 29+(Android 10+):通过 MediaStore 写入公共 Documents,
|
||||
* 无需存储权限,符合应用商店的分区存储(scoped storage)要求;
|
||||
* - API ≤ 28:直接写入公共目录(配合 manifest 中 maxSdkVersion=28 的
|
||||
* WRITE_EXTERNAL_STORAGE 权限)。
|
||||
*/
|
||||
class MainActivity : FlutterActivity() {
|
||||
private val channelName = "seqstudio/docs"
|
||||
private val folderName = "SequenceDiagram"
|
||||
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
|
||||
.setMethodCallHandler { call, result ->
|
||||
when (call.method) {
|
||||
"saveFile" -> {
|
||||
val name = call.argument<String>("name")
|
||||
val data = call.argument<ByteArray>("data")
|
||||
val mime = call.argument<String>("mime")
|
||||
if (name == null || data == null) {
|
||||
result.error("ARGS", "name/data required", null)
|
||||
} else {
|
||||
try {
|
||||
result.success(saveFile(name, data, mime))
|
||||
} catch (e: Exception) {
|
||||
result.error("WRITE", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
"listFiles" -> {
|
||||
try {
|
||||
result.success(listFiles())
|
||||
} catch (e: Exception) {
|
||||
result.error("LIST", e.message, null)
|
||||
}
|
||||
}
|
||||
"readFile" -> {
|
||||
val name = call.argument<String>("name")
|
||||
if (name == null) {
|
||||
result.error("ARGS", "name required", null)
|
||||
} else {
|
||||
try {
|
||||
result.success(readFile(name))
|
||||
} catch (e: Exception) {
|
||||
result.error("READ", e.message, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
else -> result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** MediaStore 相对路径(Q+);API ≤ 28 返回绝对路径。 */
|
||||
private fun documentsFolder(): String {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
return Environment.DIRECTORY_DOCUMENTS + "/" + folderName
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(
|
||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
||||
folderName,
|
||||
)
|
||||
if (!dir.exists()) dir.mkdirs()
|
||||
return dir.absolutePath
|
||||
}
|
||||
|
||||
/** 保存文件到公共 Documents/SequenceDiagram,返回用于展示的位置。 */
|
||||
private fun saveFile(name: String, data: ByteArray, mime: String?): String {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = contentResolver
|
||||
val collection = MediaStore.Files.getContentUri("external_primary")
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Files.FileColumns.DISPLAY_NAME, name)
|
||||
put(MediaStore.Files.FileColumns.MIME_TYPE, mime ?: "application/octet-stream")
|
||||
put(MediaStore.Files.FileColumns.RELATIVE_PATH, documentsFolder())
|
||||
put(MediaStore.Files.FileColumns.IS_PENDING, 1)
|
||||
}
|
||||
val uri: Uri = resolver.insert(collection, values)
|
||||
?: throw IllegalStateException("MediaStore insert failed")
|
||||
resolver.openOutputStream(uri)?.use { it.write(data) }
|
||||
?: throw IllegalStateException("openOutputStream failed")
|
||||
values.clear()
|
||||
values.put(MediaStore.Files.FileColumns.IS_PENDING, 0)
|
||||
resolver.update(uri, values, null, null)
|
||||
return "Documents/$folderName/$name"
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(
|
||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
||||
folderName,
|
||||
)
|
||||
if (!dir.exists()) dir.mkdirs()
|
||||
File(dir, name).writeBytes(data)
|
||||
return "Documents/$folderName/$name"
|
||||
}
|
||||
|
||||
/** 列出 Documents/SequenceDiagram 下的文件([{name, size}],新在前)。 */
|
||||
private fun listFiles(): List<Map<String, Any>> {
|
||||
val out = mutableListOf<Map<String, Any>>()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = contentResolver
|
||||
val collection = MediaStore.Files.getContentUri("external_primary")
|
||||
val projection = arrayOf(
|
||||
MediaStore.Files.FileColumns._ID,
|
||||
MediaStore.Files.FileColumns.DISPLAY_NAME,
|
||||
MediaStore.Files.FileColumns.SIZE,
|
||||
)
|
||||
val selection = "${MediaStore.Files.FileColumns.RELATIVE_PATH}=?"
|
||||
val args = arrayOf(documentsFolder() + "/")
|
||||
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
||||
val iName = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME)
|
||||
val iSize = c.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE)
|
||||
while (c.moveToNext()) {
|
||||
out.add(mapOf("name" to c.getString(iName), "size" to c.getLong(iSize)))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
val dir = File(
|
||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
||||
folderName,
|
||||
)
|
||||
if (dir.exists()) {
|
||||
dir.listFiles()?.sortedByDescending { it.lastModified() }?.forEach {
|
||||
out.add(mapOf("name" to it.name, "size" to it.length()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** 读取 Documents/SequenceDiagram 下的文件内容;不存在返回 null。 */
|
||||
private fun readFile(name: String): ByteArray? {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val resolver = contentResolver
|
||||
val collection = MediaStore.Files.getContentUri("external_primary")
|
||||
val projection = arrayOf(MediaStore.Files.FileColumns._ID)
|
||||
val selection =
|
||||
"${MediaStore.Files.FileColumns.RELATIVE_PATH}=? AND " +
|
||||
"${MediaStore.Files.FileColumns.DISPLAY_NAME}=?"
|
||||
val args = arrayOf(documentsFolder() + "/", name)
|
||||
resolver.query(collection, projection, selection, args, null)?.use { c ->
|
||||
if (c.moveToFirst()) {
|
||||
val uri = Uri.withAppendedPath(collection, c.getLong(0).toString())
|
||||
return resolver.openInputStream(uri)?.use { it.readBytes() }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
@Suppress("DEPRECATION")
|
||||
val f = File(
|
||||
File(
|
||||
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
|
||||
folderName,
|
||||
),
|
||||
name,
|
||||
)
|
||||
return if (f.exists()) f.readBytes() else null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/// 安卓公共 Documents(Documents/SequenceDiagram)读写服务。
|
||||
///
|
||||
/// 通过原生通道(MainActivity 中的 `seqstudio/docs`)实现:
|
||||
/// - Android 10+(API 29+)走 MediaStore,无需存储权限(应用商店合规);
|
||||
/// - Android 9 及以下直接写公共目录(配合 maxSdkVersion=28 的权限声明)。
|
||||
///
|
||||
/// 桌面平台不可用([isAvailable] 为 false),此时应使用应用内文件浏览器。
|
||||
library;
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
/// 安卓公共文档读写。
|
||||
class AndroidDocs {
|
||||
AndroidDocs._();
|
||||
|
||||
/// 原生通道。
|
||||
static const MethodChannel _channel = MethodChannel('seqstudio/docs');
|
||||
|
||||
/// 是否可用(仅 Android)。
|
||||
static bool get isAvailable => Platform.isAndroid;
|
||||
|
||||
/// 用于展示的目录描述。
|
||||
static const String displayDir = 'Documents/SequenceDiagram';
|
||||
|
||||
/// 保存文件到公共 Documents/SequenceDiagram,返回展示位置。
|
||||
///
|
||||
/// 参数 [name] 文件名(含后缀);[data] 文件内容;[mime] 可选 MIME 类型。
|
||||
static Future<String> saveFile(String name, Uint8List data, {String? mime}) async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('saveFile', <String, Object?>{
|
||||
'name': name,
|
||||
'data': data,
|
||||
'mime': mime,
|
||||
});
|
||||
return r as String;
|
||||
}
|
||||
|
||||
/// 列出 Documents/SequenceDiagram 下的文件(`[{name, size}]`,新在前)。
|
||||
static Future<List<Map<String, dynamic>>> listFiles() async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('listFiles');
|
||||
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。
|
||||
static Future<Uint8List?> readFile(String name) async {
|
||||
final Object? r = await _channel.invokeMethod<Object?>('readFile', <String, Object?>{
|
||||
'name': name,
|
||||
});
|
||||
if (r == null) return null;
|
||||
return r as Uint8List;
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,19 @@ class AppController extends ChangeNotifier {
|
||||
return true;
|
||||
}
|
||||
|
||||
/// 通过外部通道(如安卓公共 Documents)保存成功后标记为已保存。
|
||||
///
|
||||
/// [displayPath] 仅用于展示与状态栏;自动保存快照标记为干净,
|
||||
/// 不写 .bak 备份(外部存储不经过 dart:io)。
|
||||
Future<void> markSaved(String displayPath) async {
|
||||
_filePath = displayPath;
|
||||
_dirty = false;
|
||||
_lastSavedAt = DateTime.now();
|
||||
_status = '已保存 ${_baseName(displayPath)}';
|
||||
await Storage.instance.writeAutosave(_project, projectPath: null, clean: true);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// 从完整路径中提取文件名(兼容 `\` 与 `/` 分隔符)。
|
||||
static String _baseName(String p) => p.split(RegExp(r'[\\/]')).last;
|
||||
|
||||
|
||||
+98
-3
@@ -8,6 +8,7 @@
|
||||
// · 侧栏的“停靠 / 悬浮 / 收起为轨道”状态机;
|
||||
// · 自适应/紧凑工具栏布局(按可用宽度切换);
|
||||
// · 文件打开/保存/另存为与 SVG、PNG 导出流程。
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
@@ -19,6 +20,7 @@ import 'package:flutter/services.dart';
|
||||
import '../export/svg_writer.dart';
|
||||
import '../model/models.dart';
|
||||
import '../model/units.dart';
|
||||
import '../persistence/android_docs.dart';
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
import 'ai_dialog.dart';
|
||||
@@ -150,6 +152,30 @@ class _AppShellState extends State<AppShell> {
|
||||
|
||||
/// 打开项目:选择 .seq.json 文件并解码加载。
|
||||
Future<void> _open() async {
|
||||
// 安卓版:从公共 Documents/SequenceDiagram 打开。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => const AndroidFileDialog(
|
||||
saveMode: false,
|
||||
defaultName: '',
|
||||
suffix: '.seq.json',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
final Uint8List? bytes = await AndroidDocs.readFile(name);
|
||||
if (bytes == null) {
|
||||
if (mounted) await showMessage(context, '打开失败', '未找到文件 $name');
|
||||
return;
|
||||
}
|
||||
c.loadProject(Project.decode(utf8.decode(bytes)), path: null);
|
||||
c.setStatus('已打开 ${AndroidDocs.displayDir}/$name');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '打开失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(context, save: false, initialPath: c.filePath);
|
||||
if (path == null) return;
|
||||
try {
|
||||
@@ -162,15 +188,36 @@ class _AppShellState extends State<AppShell> {
|
||||
|
||||
/// 保存项目:已有路径则直接保存,否则转入“另存为”。
|
||||
Future<void> _save() async {
|
||||
if (c.filePath != null) {
|
||||
await c.save();
|
||||
// 安卓版:始终走“另存为”(Documents 通道),避免把展示路径当真实路径写入。
|
||||
if (AndroidDocs.isAvailable || c.filePath == null) {
|
||||
await _saveAs();
|
||||
return;
|
||||
}
|
||||
await _saveAs();
|
||||
await c.save();
|
||||
}
|
||||
|
||||
/// 另存为:选择目标路径后写入文件(同时生成 .bak 备份)。
|
||||
Future<void> _saveAs() async {
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram(MediaStore 通道)。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.seq.json',
|
||||
suffix: '.seq.json',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
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');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '保存失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
@@ -193,6 +240,30 @@ class _AppShellState extends State<AppShell> {
|
||||
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 SVG。');
|
||||
return;
|
||||
}
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.svg',
|
||||
suffix: '.svg',
|
||||
),
|
||||
);
|
||||
if (name == null) return;
|
||||
try {
|
||||
final String svg = SvgWriter(
|
||||
project: c.project,
|
||||
tokens: Tokens.of(c.brightness),
|
||||
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');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
@@ -220,6 +291,30 @@ class _AppShellState extends State<AppShell> {
|
||||
if (mounted) await showMessage(context, '未授权', '未检测到有效授权(license/*.lic),无法导出 PNG。');
|
||||
return;
|
||||
}
|
||||
// 安卓版:写入公共 Documents/SequenceDiagram。
|
||||
if (AndroidDocs.isAvailable) {
|
||||
final String? name = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => AndroidFileDialog(
|
||||
saveMode: true,
|
||||
defaultName: '${c.project.name}.png',
|
||||
suffix: '.png',
|
||||
),
|
||||
);
|
||||
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');
|
||||
} catch (e) {
|
||||
if (mounted) await showMessage(context, '导出失败', '$e');
|
||||
}
|
||||
return;
|
||||
}
|
||||
final String? path = await pickFile(
|
||||
context,
|
||||
save: true,
|
||||
|
||||
@@ -14,6 +14,7 @@ import 'package:flutter/material.dart' hide Action;
|
||||
import '../license/license_service.dart';
|
||||
import '../model/models.dart';
|
||||
import '../model/units.dart';
|
||||
import '../persistence/android_docs.dart';
|
||||
import '../persistence/storage.dart';
|
||||
import '../state/app_controller.dart';
|
||||
import '../theme/tokens.dart';
|
||||
@@ -419,6 +420,180 @@ Future<String?> pickFile(
|
||||
);
|
||||
}
|
||||
|
||||
// ===================== 安卓公共 Documents 文件对话框 =====================
|
||||
|
||||
/// 安卓版文件对话框:保存到 / 打开自公共 `Documents/SequenceDiagram`。
|
||||
///
|
||||
/// - 保存模式:输入文件名(自动补全后缀),确认后由调用方经 [AndroidDocs] 写入;
|
||||
/// - 打开模式:列出 Documents 目录中匹配后缀的文件,点选返回文件名。
|
||||
/// 返回值为文件名;取消返回 null。
|
||||
class AndroidFileDialog extends StatefulWidget {
|
||||
const AndroidFileDialog({
|
||||
super.key,
|
||||
required this.saveMode,
|
||||
required this.defaultName,
|
||||
required this.suffix,
|
||||
});
|
||||
|
||||
/// 保存(true)或打开(false)。
|
||||
final bool saveMode;
|
||||
/// 保存模式的默认文件名。
|
||||
final String defaultName;
|
||||
/// 文件后缀(过滤与自动补全)。
|
||||
final String suffix;
|
||||
|
||||
@override
|
||||
State<AndroidFileDialog> createState() => _AndroidFileDialogState();
|
||||
}
|
||||
|
||||
class _AndroidFileDialogState extends State<AndroidFileDialog> {
|
||||
late TextEditingController _name;
|
||||
List<Map<String, dynamic>> _files = <Map<String, dynamic>>[];
|
||||
bool _loading = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_name = TextEditingController(text: widget.defaultName);
|
||||
if (!widget.saveMode) _load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// 列出 Documents 目录中的匹配文件(新在前)。
|
||||
Future<void> _load() async {
|
||||
setState(() {
|
||||
_loading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final List<Map<String, dynamic>> all = await AndroidDocs.listFiles();
|
||||
final String sfx = widget.suffix.toLowerCase();
|
||||
final List<Map<String, dynamic>> matched = all
|
||||
.where((Map<String, dynamic> f) => (f['name'] as String? ?? '').toLowerCase().endsWith(sfx))
|
||||
.toList();
|
||||
if (mounted) setState(() => _files = matched);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = '无法读取 Documents 目录:$e');
|
||||
} finally {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
/// 替换其它已知后缀并补全目标后缀。
|
||||
String _ensureSuffix(String raw) {
|
||||
String n = raw.trim();
|
||||
if (n.isEmpty) return n;
|
||||
const List<String> known = <String>['.seq.json', '.json', '.svg', '.png'];
|
||||
for (final String k in known) {
|
||||
if (n.toLowerCase().endsWith(k)) {
|
||||
if (k == widget.suffix) return n;
|
||||
n = n.substring(0, n.length - k.length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return '$n${widget.suffix}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Tokens t = context.tok;
|
||||
return AlertDialog(
|
||||
backgroundColor: t.dialog,
|
||||
title: Text(widget.saveMode ? '保存到 Documents' : '从 Documents 打开'),
|
||||
content: SizedBox(
|
||||
width: 420,
|
||||
child: widget.saveMode
|
||||
? Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text('文件将保存到平板存储的 ${AndroidDocs.displayDir}/',
|
||||
style: TextStyle(color: t.dim, fontSize: 11)),
|
||||
const SizedBox(height: 10),
|
||||
TextField(
|
||||
controller: _name,
|
||||
autofocus: true,
|
||||
style: TextStyle(color: t.text, fontSize: 12.5),
|
||||
decoration: InputDecoration(
|
||||
isDense: true,
|
||||
labelText: '文件名(${widget.suffix})',
|
||||
filled: true,
|
||||
fillColor: t.panel2,
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: <Widget>[
|
||||
if (_loading)
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
)
|
||||
else if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: Text(_error!, style: TextStyle(color: t.danger, fontSize: 11.5)),
|
||||
)
|
||||
else if (_files.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(14),
|
||||
child: Text('Documents 目录中暂无 ${widget.suffix} 文件',
|
||||
style: TextStyle(color: t.dim, fontSize: 11.5)),
|
||||
)
|
||||
else
|
||||
Flexible(
|
||||
child: ListView.builder(
|
||||
shrinkWrap: true,
|
||||
itemCount: _files.length,
|
||||
itemBuilder: (BuildContext ctx, int i) {
|
||||
final Map<String, dynamic> f = _files[i];
|
||||
final String name = f['name'] as String? ?? '';
|
||||
return ListTile(
|
||||
dense: true,
|
||||
leading: Icon(Icons.description, size: 20, color: t.sub),
|
||||
title: Text(name, style: TextStyle(color: t.text, fontSize: 12)),
|
||||
onTap: () => Navigator.pop(context, name),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: widget.saveMode
|
||||
? <Widget>[
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
FilledButton(
|
||||
onPressed: () {
|
||||
final String name = _ensureSuffix(_name.text);
|
||||
if (name.isEmpty) return;
|
||||
Navigator.pop(context, name);
|
||||
},
|
||||
child: const Text('保存'),
|
||||
),
|
||||
]
|
||||
: <Widget>[
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
|
||||
if (!_loading && _error == null)
|
||||
TextButton.icon(
|
||||
onPressed: _load,
|
||||
icon: const Icon(Icons.refresh, size: 16),
|
||||
label: const Text('刷新'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ===================== 动作编辑对话框 =====================
|
||||
|
||||
/// 动作编辑对话框:修改选中动作的名称、驱动、工位、相位与颜色。
|
||||
|
||||
Reference in New Issue
Block a user